codekingpro commited on
Commit
551fc67
·
verified ·
1 Parent(s): 1531e28

Add files using upload-large-folder tool

Browse files
7zip/History.txt ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ HISTORY of the 7-Zip
2
+ --------------------
3
+
4
+ This file contains information about changes for latest versions of 7-Zip.
5
+ The full changelog file can be downloaded here:
6
+ https://7-zip.org/history.txt
7
+
8
+ 26.01 2026-04-27
9
+ -------------------------
10
+ - linux version of 7-Zip can use huge pages (2 MB pages). It can increase compression
11
+ speed for 10% for 7z/xz/LZMA/LZMA2 compression.
12
+ - new -spo[d|c|r] switch specifies the path generation mode for the output directory
13
+ for archive extraction. The output directory path is generated from the path specified
14
+ in the -o{dir_path} switch and the name of the archive being unpacked.
15
+ -spod : for Linux/Posix/macOS: -o{dir_path} specifies the direct path to the output directory.
16
+ The asterisk (*) character in {dir_path} will not be replaced by the archive name.
17
+ -spoc : 7-Zip will concatenate the path specified in -o{dir_path} with the archive name
18
+ to form the final path to the output directory.
19
+ -spor : 7-Zip will replace asterisk (*) character in the path specified in the -o{dir_path}
20
+ with the archive name. This is the default option.
21
+ - some bugs were fixed.
22
+
23
+
24
+ 26.00 2026-02-12
25
+ -------------------------
26
+ - improved code for ZIP, CPIO, RAR, UFD, QCOW, Compound.
27
+ - 7-Zip File Manager: improved sorting order of the file list. It uses file name as secondary sorting key.
28
+ - 7-Zip File Manager: improved Benchmark to support systems with more than 64 CPU threads.
29
+ - the bug was fixed: 7-Zip could not correctly extract TAR archives containing sparse files.
30
+ - some bugs were fixed.
31
+
32
+
33
+ 25.01 2025-08-03
34
+ -------------------------
35
+ - CVE-2025-55188 : The code for handling symbolic links has been changed
36
+ to provide greater security when extracting files from archives.
37
+ Command line switch -snld20 can be used to bypass default security
38
+ checks when creating symbolic links.
39
+
40
+
41
+ 25.00 2025-07-05
42
+ -------------------------
43
+ - 7-Zip for Windows can now use more than 64 CPU threads for compression
44
+ to zip/7z/xz archives and for the 7-Zip benchmark.
45
+ If there are more than one processor group in Windows (on systems with more than
46
+ 64 cpu threads), 7-Zip distributes running CPU threads across different processor groups.
47
+ - bzip2 compression speed was increased by 15-40%.
48
+ - deflate (zip/gz) compression speed was increased by 1-3%.
49
+ - improved support for zip, cpio and fat archives.
50
+ - fixed some bugs.
51
+ - CVE-2025-11001 and CVE-2025-11002 : A vulnerability was fixed for symbolic links processing,
52
+ when extracting files from archives.
53
+ - the bug was fixed : CVE-2025-53816 : 7-Zip could work incorrectly for some incorrect RAR archives.
54
+ - the bug was fixed : CVE-2025-53817 : 7-Zip could crash for some incorrect COM (Compound File) archives.
55
+
56
+
57
+ 24.09 2024-11-29
58
+ -------------------------
59
+ - The default dictionary size values for LZMA/LZMA2 compression methods were increased:
60
+ dictionary size compression level
61
+ v24.08 v24.09 v24.09
62
+ 32-bit 64-bit
63
+ 8 MB 16 MB 16 MB -mx4
64
+ 16 MB 32 MB 32 MB -mx5 : Normal
65
+ 32 MB 64 MB 64 MB -mx6
66
+ 32 MB 64 MB 128 MB -mx7 : Maximum
67
+ 64 MB 64 MB 256 MB -mx8
68
+ 64 MB 64 MB 256 MB -mx9 : Ultra
69
+ The default dictionary size values for 32-bit versions of LZMA/LZMA2 don't exceed 64 MB.
70
+ - 7-Zip now can calculate the following hash checksums: SHA-512, SHA-384, SHA3-256 and MD5.
71
+ - APM and HFS support was improved.
72
+ - If an archive update operation uses a temporary archive folder and
73
+ the archive is moved to the destination folder, 7-Zip shows the progress of moving
74
+ the archive file, as this operation can take a long time if the archive is large.
75
+ - The bug was fixed: 7-Zip File Manager didn't propagate Zone.Identifier stream
76
+ for extracted files from nested archives (if there is open archive inside another open archive).
77
+ - Some bugs were fixed.
78
+
79
+
80
+ 24.08 2024-08-11
81
+ -------------------------
82
+ - The bug in 7-Zip 24.00-24.07 was fixed:
83
+ For creating a zip archive: 7-Zip could write extra zero bytes after the end of the archive,
84
+ if a file included to archive cannot be compressed to a size smaller than original.
85
+ The created zip archive is correct except for the useless zero bytes after the end of the archive.
86
+ When unpacking such a zip archive, 7-Zip displays a warning:
87
+ "WARNING: There are data after the end of archive".
88
+ - The bug was fixed: there was a leak of GDI objects (internal resources in Windows)
89
+ in "Confirm File Replace" window, causing problems after 1600 displays of "Confirm File Replace"
90
+ window from same running 7-Zip process.
91
+ - Some optimizations for displaying file icons in 7-Zip File Manager and in "Confirm File Replace" window.
92
+ - Some bugs were fixed. CVE-2024-11612.
93
+
94
+
95
+ 24.07 2024-06-19
96
+ -------------------------
97
+ - The bug was fixed: 7-Zip could crash for some incorrect ZSTD archives (CVE-2024-11477).
98
+
99
+
100
+ 24.06 2024-05-26
101
+ -------------------------
102
+ - The bug was fixed: 7-Zip could not unpack some ZSTD archives.
103
+
104
+
105
+ 24.05 2024-05-14
106
+ -------------------------
107
+ - New switch -myv={MMNN} to set decoder compatibility version for 7z archive creating.
108
+ {MMNN} is 4-digit number that represents the version of 7-Zip without a dot.
109
+ If -myv={MMNN} switch is specified, 7-Zip will only use compression methods that can
110
+ be decoded by the specified version {MMNN} of 7-Zip and newer versions.
111
+ If -myv={MMNN} switch is not specified, -myv=2300 is used, and 7-Zip will only
112
+ use compression methods that can be decoded by 7-Zip 23.00 and newer versions.
113
+ - New switch -myfa={FilterID} to allow 7-Zip to use the specified filter method for 7z archive creating.
114
+ - New switch -myfd={FilterID} to disallow 7-Zip to use the specified filter method for 7z archive creating.
115
+ - Some bugs were fixed.
116
+
117
+
118
+ 24.04 2024-04-05
119
+ -------------------------
120
+ - New menu item in 7-Zip File Manager: "Tools / Delete Temporary Files...".
121
+ This menu item opens a window showing temporary folders and files
122
+ created by 7-Zip in the user's "Temp" folder on a Windows system.
123
+ In this window, the user can delete temporary files.
124
+
125
+
126
+ 24.03 2024-03-23
127
+ -------------------------
128
+ - 7-Zip now can use new RISCV filter for compression to 7z and xz archives.
129
+ RISCV filter can increase compression ratio for data containing executable
130
+ files compiled for RISC-V architecture.
131
+ - The speed for LZMA and LZMA2 decompression in ARM64 version for Windows
132
+ was increased by 20%-60%.
133
+ - 7-Zip GUI and 7-Zip File Manager can ask user permission to unpack RAR archives that
134
+ require big amount of memory, if the dictionary size in RAR archive is larger than 4 GB.
135
+ - new switch -smemx{size}g : to set allowed memory usage limit for RAR archive unpacking.
136
+ RAR archives can use dictionary up 64 GB. Default allowed limit for RAR unpacking is 4 GB.
137
+ - 7zg.exe (7-Zip GUI): -y switch disables user requests and messages.
138
+ - 7-Zip shows hash methods XXH64 and BLAKE2sp in context menu.
139
+ - -slmu switch : to show timestamps as UTC instead of LOCAL TIME.
140
+ - -slsl switch : in console 7-Zip for Windows : to show file paths with
141
+ linux path separator slash '/' instead of backslash separator '\'.
142
+ - 7-Zip supports .sha256 files that use backslash path separator '\'.
143
+ - Some bugs were fixed.
144
+
145
+
146
+ 24.01 2024-01-31
147
+ -------------------------
148
+ - 7-Zip now can unpack ZSTD archives (.zst filename extension).
149
+ - 7-Zip now can unpack ZIP, SquashFS and RPM archives that use ZSTD compression method.
150
+ - 7-Zip now supports fast hash algorithm XXH64 that is used in ZSTD.
151
+ - 7-Zip now can unpack RAR archives (that use larger than 4 GB dictionary) created by new WinRAR 7.00.
152
+ - 7-Zip now can unpack DMG archives that use XZ (ULMO/LZMA) compression method.
153
+ - 7-Zip now can unpack NTFS images with cluster size larger than 64 KB.
154
+ - 7-Zip now can unpack MBR and GPT images with 4 KB sectors.
155
+ - Speed optimizations for archive unpacking: rar, cab, wim, zip, gz.
156
+ - Speed optimizations for hash caclulation: CRC-32, CRC-64, BLAKE2sp.
157
+ - The bug was fixed: 7-Zip for Linux could fail for multivolume creation in some cases.
158
+ - Some bugs were fixed.
159
+
160
+
161
+ 23.01 2023-06-20
162
+ -------------------------
163
+ - The page "Language" in 7-Zip's menu Tools/Options now shows information
164
+ about selected translation, including the number of translated lines.
165
+ - Some bugs were fixed.
166
+
167
+
168
+ 23.00 2023-05-07
169
+ -------------------------
170
+ - 7-Zip now can use new ARM64 filter for compression to 7z and xz archives.
171
+ ARM64 filter can increase compression ratio for data containing executable
172
+ files compiled for ARM64 (AArch64) architecture.
173
+ Also 7-Zip now parses executable files (that have exe and dll filename extensions)
174
+ before compressing, and it selects appropriate filter for each parsed file:
175
+ - BCJ or BCJ2 filter for x86 executable files,
176
+ - ARM64 filter for ARM64 executable files.
177
+ Previous versions by default used x86 filter BCJ or BCJ2 for all exe/dll files.
178
+ - Default section size for BCJ2 filter was changed from 64 MiB to 240 MiB.
179
+ It can increase compression ratio for executable files larger than 64 MiB.
180
+ - UDF: support was improved.
181
+ - cpio: support for hard links.
182
+ - Some changes and optimizations in WIM creation code.
183
+ - When new 7-Zip creates multivolume archive, 7-Zip keeps in open state
184
+ only volumes that still can be changed. Previous versions kept all volumes
185
+ in open state until the end of the archive creation.
186
+ - 7-Zip for Linux and macOS now can reduce the number of simultaneously open files,
187
+ when 7-Zip opens, extracts or creates multivolume archive. It allows to avoid
188
+ the failures for cases with big number of volumes, bacause there is a limitation
189
+ for number of open files allowed for a single program in Linux and macOS.
190
+ - There are optimizations in code for 7-Zip's context menu in Explorer:
191
+ the speed of preparing of the menu showing was improved for cases when big number of
192
+ files were selected by external program for context menu that contains 7-Zip menu commands.
193
+ - There are changes in code for the drag-and-drop operations to and from 7-Zip File Manager.
194
+ And the drag-and-drop operation with right button of mouse now is supported for some cases.
195
+ - The bugs were fixed:
196
+ - ZIP archives: if multithreaded zip compression was performed with more than one
197
+ file to stdout stream (-so switch), 7-Zip didn't write "data descriptor" for some files.
198
+ - ext4 archives: 7-Zip couldn't correctly extract symbolic link to directory from ext4 archives.
199
+ - HFS and APFS archives: 7-Zip incorrectly decoded uncompressed blocks (64 KiB) in compressed forks.
200
+ - HFS : zlib without Adler supported
201
+ - Some another bugs were fixed.
202
+
203
+
204
+ ==
205
+ End of document
7zip/License.txt ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 7-Zip
2
+ ~~~~~
3
+ License for use and distribution
4
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
+
6
+ 7-Zip Copyright (C) 1999-2026 Igor Pavlov.
7
+
8
+ The licenses for files are:
9
+
10
+ - 7z.dll:
11
+ - The "GNU LGPL" as main license for most of the code
12
+ - The "GNU LGPL" with "unRAR license restriction" for some code
13
+ - The "BSD 3-clause License" for some code
14
+ - The "BSD 2-clause License" for some code
15
+ - All other files: the "GNU LGPL".
16
+
17
+ Redistributions in binary form must reproduce related license information from this file.
18
+
19
+ Note:
20
+ You can use 7-Zip on any computer, including a computer in a commercial
21
+ organization. You don't need to register or pay for 7-Zip.
22
+
23
+
24
+ GNU LGPL information
25
+ --------------------
26
+
27
+ This library is free software; you can redistribute it and/or
28
+ modify it under the terms of the GNU Lesser General Public
29
+ License as published by the Free Software Foundation; either
30
+ version 2.1 of the License, or (at your option) any later version.
31
+
32
+ This library is distributed in the hope that it will be useful,
33
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
34
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
35
+ Lesser General Public License for more details.
36
+
37
+ You can receive a copy of the GNU Lesser General Public License from
38
+ http://www.gnu.org/
39
+
40
+
41
+
42
+
43
+ BSD 3-clause License in 7-Zip code
44
+ ----------------------------------
45
+
46
+ The "BSD 3-clause License" is used for the following code in 7z.dll
47
+ 1) LZFSE data decompression.
48
+ That code was derived from the code in the "LZFSE compression library" developed by Apple Inc,
49
+ that also uses the "BSD 3-clause License".
50
+ 2) ZSTD data decompression.
51
+ that code was developed using original zstd decoder code as reference code.
52
+ The original zstd decoder code was developed by Facebook Inc,
53
+ that also uses the "BSD 3-clause License".
54
+
55
+ Copyright (c) 2015-2016, Apple Inc. All rights reserved.
56
+ Copyright (c) Facebook, Inc. All rights reserved.
57
+ Copyright (c) 2023-2026 Igor Pavlov.
58
+
59
+ Text of the "BSD 3-clause License"
60
+ ----------------------------------
61
+
62
+ Redistribution and use in source and binary forms, with or without modification,
63
+ are permitted provided that the following conditions are met:
64
+
65
+ 1. Redistributions of source code must retain the above copyright notice, this
66
+ list of conditions and the following disclaimer.
67
+
68
+ 2. Redistributions in binary form must reproduce the above copyright notice,
69
+ this list of conditions and the following disclaimer in the documentation
70
+ and/or other materials provided with the distribution.
71
+
72
+ 3. Neither the name of the copyright holder nor the names of its contributors may
73
+ be used to endorse or promote products derived from this software without
74
+ specific prior written permission.
75
+
76
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
77
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
78
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
79
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
80
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
81
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
82
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
83
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
84
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
85
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
86
+
87
+ ---
88
+
89
+
90
+
91
+
92
+ BSD 2-clause License in 7-Zip code
93
+ ----------------------------------
94
+
95
+ The "BSD 2-clause License" is used for the XXH64 code in 7-Zip.
96
+
97
+ XXH64 code in 7-Zip was derived from the original XXH64 code developed by Yann Collet.
98
+
99
+ Copyright (c) 2012-2021 Yann Collet.
100
+ Copyright (c) 2023-2026 Igor Pavlov.
101
+
102
+ Text of the "BSD 2-clause License"
103
+ ----------------------------------
104
+
105
+ Redistribution and use in source and binary forms, with or without modification,
106
+ are permitted provided that the following conditions are met:
107
+
108
+ 1. Redistributions of source code must retain the above copyright notice, this
109
+ list of conditions and the following disclaimer.
110
+
111
+ 2. Redistributions in binary form must reproduce the above copyright notice,
112
+ this list of conditions and the following disclaimer in the documentation
113
+ and/or other materials provided with the distribution.
114
+
115
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
116
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
117
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
118
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
119
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
120
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
121
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
122
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
123
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
124
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
125
+
126
+ ---
127
+
128
+
129
+
130
+
131
+ unRAR license restriction
132
+ -------------------------
133
+
134
+ The decompression engine for RAR archives was developed using source
135
+ code of unRAR program.
136
+ All copyrights to original unRAR code are owned by Alexander Roshal.
137
+
138
+ The license for original unRAR code has the following restriction:
139
+
140
+ The unRAR sources cannot be used to re-create the RAR compression algorithm,
141
+ which is proprietary. Distribution of modified unRAR sources in separate form
142
+ or as a part of other software is permitted, provided that it is clearly
143
+ stated in the documentation and source comments that the code may
144
+ not be used to develop a RAR (WinRAR) compatible archiver.
145
+
146
+ --
7zip/Uninstall.exe ADDED
Binary file (17.4 kB). View file
 
7zip/descript.ion ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 7-zip.chm 7-Zip Help
2
+ 7-Zip.dll 7-Zip Plugin
3
+ 7-Zip32.dll 7-Zip Plugin 32-bit
4
+ 7z.dll 7-Zip Engine
5
+ 7z.exe 7-Zip Console
6
+ 7z.sfx 7-Zip GUI SFX
7
+ 7zCon.sfx 7-Zip Console SFX
8
+ 7zFM.exe 7-Zip File Manager
9
+ 7zg.exe 7-Zip GUI
10
+ descript.ion 7-Zip File Descriptions
11
+ history.txt 7-Zip History
12
+ Lang 7-Zip Translations
13
+ license.txt 7-Zip License
14
+ readme.txt 7-Zip Overview
7zip/readme.txt ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 7-Zip 26.01
2
+ -----------
3
+
4
+ 7-Zip is a file archiver for Windows.
5
+
6
+ 7-Zip Copyright (C) 1999-2026 Igor Pavlov.
7
+
8
+ The main features of 7-Zip:
9
+
10
+ - High compression ratio in the new 7z format
11
+ - Supported formats:
12
+ - Packing / unpacking: 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIM.
13
+ - Unpacking only: APFS, AR, ARJ, Base64, CAB, CHM, CPIO, CramFS, DMG, EXT, FAT, GPT, HFS,
14
+ IHEX, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, QCOW2, RAR,
15
+ RPM, SquashFS, UDF, UEFI, VDI, VHD, VHDX, VMDK, XAR, Z and ZSTD.
16
+ - Fast compression and decompression
17
+ - Self-extracting capability for 7z format
18
+ - Strong AES-256 encryption in 7z and ZIP formats
19
+ - Integration with Windows Shell
20
+ - Powerful File Manager
21
+ - Powerful command line version
22
+ - Localizations for 90 languages
23
+
24
+
25
+ 7-Zip is free software distributed under the GNU LGPL (except for unRar code).
26
+ Read License.txt for more information about license.
27
+
28
+
29
+ This distribution package contains the following files:
30
+
31
+ 7zFM.exe - 7-Zip File Manager
32
+ 7-zip.dll - Plugin for Windows Shell
33
+ 7-zip32.dll - Plugin for Windows Shell (32-bit plugin for 64-bit system)
34
+ 7zg.exe - GUI module
35
+ 7z.exe - Command line version
36
+ 7z.dll - 7-Zip engine module
37
+ 7z.sfx - SFX module (Windows version)
38
+ 7zCon.sfx - SFX module (Console version)
39
+
40
+ License.txt - License information
41
+ readme.txt - This file
42
+ History.txt - History of 7-Zip
43
+ 7-zip.chm - User's Manual in HTML Help format
44
+ descript.ion - Description for files
45
+
46
+ Lang\en.ttt - English (base) localization file
47
+ Lang\*.txt - Localization files
48
+
49
+
50
+ ---
51
+ End of document
7zip/vcruntime140_1.dll ADDED
Binary file (49.8 kB). View file
 
android-sdk/.knownPackages ADDED
@@ -0,0 +1 @@
 
 
1
+ �/�[<�+ȝ�N�{~�
git/usr/share/perl5/core_perl/Term/Table.pm ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Term::Table;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '0.024';
6
+
7
+ use Term::Table::Cell();
8
+
9
+ use Term::Table::Util qw/term_size uni_length USE_GCS/;
10
+ use Scalar::Util qw/blessed/;
11
+ use List::Util qw/max sum/;
12
+ use Carp qw/croak carp/;
13
+
14
+ use Term::Table::HashBase qw/rows _columns collapse max_width mark_tail sanitize show_header auto_columns no_collapse header allow_overflow pad/;
15
+
16
+ sub BORDER_SIZE() { 4 } # '| ' and ' |' borders
17
+ sub DIV_SIZE() { 3 } # ' | ' column delimiter
18
+ sub CELL_PAD_SIZE() { 2 } # space on either side of the |
19
+
20
+ sub init {
21
+ my $self = shift;
22
+
23
+ croak "You cannot have a table with no rows"
24
+ unless $self->{+ROWS} && @{$self->{+ROWS}};
25
+
26
+ $self->{+MAX_WIDTH} ||= term_size();
27
+ $self->{+NO_COLLAPSE} ||= {};
28
+ if (ref($self->{+NO_COLLAPSE}) eq 'ARRAY') {
29
+ $self->{+NO_COLLAPSE} = {map { ($_ => 1) } @{$self->{+NO_COLLAPSE}}};
30
+ }
31
+
32
+ if ($self->{+NO_COLLAPSE} && $self->{+HEADER}) {
33
+ my $header = $self->{+HEADER};
34
+ for(my $idx = 0; $idx < @$header; $idx++) {
35
+ $self->{+NO_COLLAPSE}->{$idx} ||= $self->{+NO_COLLAPSE}->{$header->[$idx]};
36
+ }
37
+ }
38
+
39
+ $self->{+PAD} = 4 unless defined $self->{+PAD};
40
+
41
+ $self->{+COLLAPSE} = 1 unless defined $self->{+COLLAPSE};
42
+ $self->{+SANITIZE} = 1 unless defined $self->{+SANITIZE};
43
+ $self->{+MARK_TAIL} = 1 unless defined $self->{+MARK_TAIL};
44
+
45
+ if($self->{+HEADER}) {
46
+ $self->{+SHOW_HEADER} = 1 unless defined $self->{+SHOW_HEADER};
47
+ }
48
+ else {
49
+ $self->{+HEADER} = [];
50
+ $self->{+AUTO_COLUMNS} = 1;
51
+ $self->{+SHOW_HEADER} = 0;
52
+ }
53
+ }
54
+
55
+ sub columns {
56
+ my $self = shift;
57
+
58
+ $self->regen_columns unless $self->{+_COLUMNS};
59
+
60
+ return $self->{+_COLUMNS};
61
+ }
62
+
63
+ sub regen_columns {
64
+ my $self = shift;
65
+
66
+ my $has_header = $self->{+SHOW_HEADER} && @{$self->{+HEADER}};
67
+ my %new_col = (width => 0, count => $has_header ? -1 : 0);
68
+
69
+ my $cols = [map { {%new_col} } @{$self->{+HEADER}}];
70
+ my @rows = @{$self->{+ROWS}};
71
+
72
+ for my $row ($has_header ? ($self->{+HEADER}, @rows) : (@rows)) {
73
+ for my $ci (0 .. max(@$cols - 1, @$row - 1)) {
74
+ $cols->[$ci] ||= {%new_col} if $self->{+AUTO_COLUMNS};
75
+ my $c = $cols->[$ci] or next;
76
+ $c->{idx} ||= $ci;
77
+ $c->{rows} ||= [];
78
+
79
+ my $r = $row->[$ci];
80
+ $r = Term::Table::Cell->new(value => $r)
81
+ unless blessed($r)
82
+ && ($r->isa('Term::Table::Cell')
83
+ || $r->isa('Term::Table::CellStack')
84
+ || $r->isa('Term::Table::Spacer'));
85
+
86
+ $r->sanitize if $self->{+SANITIZE};
87
+ $r->mark_tail if $self->{+MARK_TAIL};
88
+
89
+ my $rs = $r->width;
90
+ $c->{width} = $rs if $rs > $c->{width};
91
+ $c->{count}++ if $rs;
92
+
93
+ push @{$c->{rows}} => $r;
94
+ }
95
+ }
96
+
97
+ # Remove any empty columns we can
98
+ @$cols = grep {$_->{count} > 0 || $self->{+NO_COLLAPSE}->{$_->{idx}}} @$cols
99
+ if $self->{+COLLAPSE};
100
+
101
+ my $current = sum(map {$_->{width}} @$cols);
102
+ my $border = sum(BORDER_SIZE, $self->{+PAD}, DIV_SIZE * (@$cols - 1));
103
+ my $total = $current + $border;
104
+
105
+ if ($total > $self->{+MAX_WIDTH}) {
106
+ my $fair = ($self->{+MAX_WIDTH} - $border) / @$cols;
107
+ if ($fair < 1) {
108
+ return $self->{+_COLUMNS} = $cols if $self->{+ALLOW_OVERFLOW};
109
+ croak "Table is too large ($total including $self->{+PAD} padding) to fit into max-width ($self->{+MAX_WIDTH})";
110
+ }
111
+
112
+ my $under = 0;
113
+ my @fix;
114
+ for my $c (@$cols) {
115
+ if ($c->{width} > $fair) {
116
+ push @fix => $c;
117
+ }
118
+ else {
119
+ $under += $c->{width};
120
+ }
121
+ }
122
+
123
+ # Recalculate fairness
124
+ $fair = int(($self->{+MAX_WIDTH} - $border - $under) / @fix);
125
+ if ($fair < 1) {
126
+ return $self->{+_COLUMNS} = $cols if $self->{+ALLOW_OVERFLOW};
127
+ croak "Table is too large ($total including $self->{+PAD} padding) to fit into max-width ($self->{+MAX_WIDTH})";
128
+ }
129
+
130
+ # Adjust over-long columns
131
+ $_->{width} = $fair for @fix;
132
+ }
133
+
134
+ $self->{+_COLUMNS} = $cols;
135
+ }
136
+
137
+ sub render {
138
+ my $self = shift;
139
+
140
+ my $cols = $self->columns;
141
+ for my $col (@$cols) {
142
+ for my $cell (@{$col->{rows}}) {
143
+ $cell->reset;
144
+ }
145
+ }
146
+ my $width = sum(BORDER_SIZE, $self->{+PAD}, DIV_SIZE * @$cols, map { $_->{width} } @$cols);
147
+
148
+ #<<< NO-TIDY
149
+ my $border = '+' . join('+', map { '-' x ($_->{width} + CELL_PAD_SIZE) } @$cols) . '+';
150
+ my $template = '|' . join('|', map { my $w = $_->{width} + CELL_PAD_SIZE; '%s' } @$cols) . '|';
151
+ my $spacer = '|' . join('|', map { ' ' x ($_->{width} + CELL_PAD_SIZE) } @$cols) . '|';
152
+ #>>>
153
+
154
+ my @out = ($border);
155
+ my ($row, $split, $found) = (0, 0, 0);
156
+ while(1) {
157
+ my @row;
158
+
159
+ my $is_spacer = 0;
160
+
161
+ for my $col (@$cols) {
162
+ my $r = $col->{rows}->[$row];
163
+ unless($r) {
164
+ push @row => '';
165
+ next;
166
+ }
167
+
168
+ my ($v, $vw);
169
+
170
+ if ($r->isa('Term::Table::Cell')) {
171
+ my $lw = $r->border_left_width;
172
+ my $rw = $r->border_right_width;
173
+ $vw = $col->{width} - $lw - $rw;
174
+ $v = $r->break->next($vw);
175
+ }
176
+ elsif ($r->isa('Term::Table::CellStack')) {
177
+ ($v, $vw) = $r->break->next($col->{width});
178
+ }
179
+ elsif ($r->isa('Term::Table::Spacer')) {
180
+ $is_spacer = 1;
181
+ }
182
+
183
+ if ($is_spacer) {
184
+ last;
185
+ }
186
+ elsif (defined $v) {
187
+ $found++;
188
+ my $bcolor = $r->border_color || '';
189
+ my $vcolor = $r->value_color || '';
190
+ my $reset = $r->reset_color || '';
191
+
192
+ if (my $need = $vw - uni_length($v)) {
193
+ $v .= ' ' x $need;
194
+ }
195
+
196
+ my $rt = "${reset}${bcolor}\%s${reset} ${vcolor}\%s${reset} ${bcolor}\%s${reset}";
197
+ push @row => sprintf($rt, $r->border_left || '', $v, $r->border_right || '');
198
+ }
199
+ else {
200
+ push @row => ' ' x ($col->{width} + 2);
201
+ }
202
+ }
203
+
204
+ if (!grep {$_ && m/\S/} @row) {
205
+ last unless $found || $is_spacer;
206
+
207
+ push @out => $border if $row == 0 && $self->{+SHOW_HEADER} && @{$self->{+HEADER}};
208
+ push @out => $spacer if $split > 1 || $is_spacer;
209
+
210
+ $row++;
211
+ $split = 0;
212
+ $found = 0;
213
+
214
+ next;
215
+ }
216
+
217
+ if ($split == 1 && @out > 1 && $out[-2] ne $border && $out[-2] ne $spacer) {
218
+ my $last = pop @out;
219
+ push @out => ($spacer, $last);
220
+ }
221
+
222
+ push @out => sprintf($template, @row);
223
+ $split++;
224
+ }
225
+
226
+ pop @out while @out && $out[-1] eq $spacer;
227
+
228
+ unless (USE_GCS) {
229
+ for my $row (@out) {
230
+ next unless $row =~ m/[[:^ascii:]]/;
231
+ unshift @out => "Unicode::GCString is not installed, table may not display all unicode characters properly";
232
+ last;
233
+ }
234
+ }
235
+
236
+ return (@out, $border);
237
+ }
238
+
239
+ sub display {
240
+ my $self = shift;
241
+ my ($fh) = @_;
242
+
243
+ my @parts = map "$_\n", $self->render;
244
+
245
+ print $fh @parts if $fh;
246
+ print @parts;
247
+ }
248
+
249
+ 1;
250
+
251
+ __END__
252
+
253
+
254
+ =pod
255
+
256
+ =encoding UTF-8
257
+
258
+ =head1 NAME
259
+
260
+ Term::Table - Format a header and rows into a table
261
+
262
+ =head1 DESCRIPTION
263
+
264
+ This is used by some failing tests to provide diagnostics about what has gone
265
+ wrong. This module is able to format rows of data into tables.
266
+
267
+ =head1 SYNOPSIS
268
+
269
+ use Term::Table;
270
+
271
+ my $table = Term::Table->new(
272
+ max_width => 80, # Defaults to terminal size
273
+ pad => 4, # Extra padding between table and max-width (defaults to 4)
274
+ allow_overflow => 0, # Default is 0, when off an exception will be thrown if the table is too big
275
+ collapse => 1, # Do not show empty columns
276
+
277
+ header => ['name', 'age', 'hair color'],
278
+ rows => [
279
+ ['Fred Flintstone', 2000000, 'black'],
280
+ ['Wilma Flintstone', 1999995, 'red'],
281
+ ...
282
+ ],
283
+ );
284
+
285
+ say $_ for $table->render;
286
+
287
+ This prints a table like this:
288
+
289
+ +------------------+---------+------------+
290
+ | name | age | hair color |
291
+ +------------------+---------+------------+
292
+ | Fred Flintstone | 2000000 | black |
293
+ | Wilma Flintstone | 1999995 | red |
294
+ | ... | ... | ... |
295
+ +------------------+---------+------------+
296
+
297
+ =head1 INTERFACE
298
+
299
+ use Term::Table;
300
+ my $table = Term::Table->new(...);
301
+
302
+ =head2 OPTIONS
303
+
304
+ =over 4
305
+
306
+ =item header => [ ... ]
307
+
308
+ If you want a header specify it here.
309
+ This takes an arrayref with each columns heading.
310
+
311
+ =item rows => [ [...], [...], ... ]
312
+
313
+ This should be an arrayref containing an arrayref per row.
314
+
315
+ =item collapse => $bool
316
+
317
+ Use this if you want to hide empty columns, that is any column that has no data
318
+ in any row. Having a header for the column will not effect collapse.
319
+
320
+ =item max_width => $num
321
+
322
+ Set the maximum width of the table, the table may not be this big, but it will
323
+ be no bigger. If none is specified it will attempt to find the width of your
324
+ terminal and use that, otherwise it falls back to the terminal width or C<80>.
325
+
326
+ =item pad => $num
327
+
328
+ Defaults to C<4>, extra padding for row width calculations.
329
+ Default is for legacy support.
330
+ Set this to C<0> to turn padding off.
331
+
332
+ =item allow_overflow => $bool
333
+
334
+ Defaults to C<0>. If this is off then an exception will be thrown if the table
335
+ cannot be made to fit inside the max-width. If this is set to C<1> then the
336
+ table will be rendered anyway, larger than max-width, if it is not possible
337
+ to stay within the max-width. In other words this turns max-width from a
338
+ hard-limit to a soft recommendation.
339
+
340
+ =item sanitize => $bool
341
+
342
+ This will sanitize all the data in the table such that newlines, control
343
+ characters, and all whitespace except for ASCII 20 C<' '> are replaced with
344
+ escape sequences. This prevents newlines, tabs, and similar whitespace from
345
+ disrupting the table.
346
+
347
+ B<Note:> newlines are marked as C<\n>, but a newline is also inserted into the
348
+ data so that it typically displays in a way that is useful to humans.
349
+
350
+ Example:
351
+
352
+ my $field = "foo\nbar\nbaz\n";
353
+
354
+ print join "\n" => table(
355
+ sanitize => 1,
356
+ rows => [
357
+ [$field, 'col2' ],
358
+ ['row2 col1', 'row2 col2']
359
+ ]
360
+ );
361
+
362
+ Prints:
363
+
364
+ +-----------------+-----------+
365
+ | foo\n | col2 |
366
+ | bar\n | |
367
+ | baz\n | |
368
+ | | |
369
+ | row2 col1 | row2 col2 |
370
+ +-----------------+-----------+
371
+
372
+ So it marks the newlines by inserting the escape sequence, but it also shows
373
+ the data across as many lines as it would normally display.
374
+
375
+ =item mark_tail => $bool
376
+
377
+ This will replace the last whitespace character of any trailing whitespace with
378
+ its escape sequence. This makes it easier to notice trailing whitespace when
379
+ comparing values.
380
+
381
+ =item show_header => $bool
382
+
383
+ Set this to false to hide the header. This defaults to true if the header is
384
+ set, false if no header is provided.
385
+
386
+ =item auto_columns => $bool
387
+
388
+ Set this to true to automatically add columns that are not named in the header.
389
+ This defaults to false if a header is provided, and defaults to true when there
390
+ is no header.
391
+
392
+ =item no_collapse => [ $col_num_a, $col_num_b, ... ]
393
+
394
+ =item no_collapse => [ $col_name_a, $col_name_b, ... ]
395
+
396
+ =item no_collapse => { $col_num_a => 1, $col_num_b => 1, ... }
397
+
398
+ =item no_collapse => { $col_name_a => 1, $col_name_b => 1, ... }
399
+
400
+ Specify (by number and/or name) columns that should not be removed when empty.
401
+ The 'name' form only works when a header is specified. There is currently no
402
+ protection to insure that names you specify are actually in the header, invalid
403
+ names are ignored, patches to fix this will be happily accepted.
404
+
405
+ =back
406
+
407
+ =head1 NOTE ON UNICODE/WIDE CHARACTERS
408
+
409
+ Some unicode characters, such as C<婧> (C<U+5A67>) are wider than others. These
410
+ will render just fine if you C<use utf8;> as necessary, and
411
+ L<Unicode::GCString> is installed, however if the module is not installed there
412
+ will be anomalies in the table:
413
+
414
+ +-----+-----+---+
415
+ | a | b | c |
416
+ +-----+-----+---+
417
+ | 婧 | x | y |
418
+ | x | y | z |
419
+ | x | 婧 | z |
420
+ +-----+-----+---+
421
+
422
+ =head1 SOURCE
423
+
424
+ The source code repository for C<Term-Table> can be found at
425
+ L<https://github.com/exodist/Term-Table/>.
426
+
427
+ =head1 MAINTAINERS
428
+
429
+ =over 4
430
+
431
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
432
+
433
+ =back
434
+
435
+ =head1 AUTHORS
436
+
437
+ =over 4
438
+
439
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
440
+
441
+ =back
442
+
443
+ =head1 COPYRIGHT
444
+
445
+ Copyright 2016 Chad Granum E<lt>exodist@cpan.orgE<gt>.
446
+
447
+ This program is free software; you can redistribute it and/or
448
+ modify it under the same terms as Perl itself.
449
+
450
+ See L<https://dev.perl.org/licenses/>
451
+
452
+ =cut
git/usr/share/perl5/core_perl/Test/Builder.pm ADDED
@@ -0,0 +1,2646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test::Builder;
2
+
3
+ use 5.006;
4
+ use strict;
5
+ use warnings;
6
+
7
+ our $VERSION = '1.302210';
8
+
9
+ use Scalar::Util qw/blessed reftype weaken/;
10
+
11
+ use Test2::Util qw/USE_THREADS try get_tid/;
12
+ use Test2::API qw/context release/;
13
+ # Make Test::Builder thread-safe for ithreads.
14
+ BEGIN {
15
+ warn "Test::Builder was loaded after Test2 initialization, this is not recommended."
16
+ if Test2::API::test2_init_done() || Test2::API::test2_load_done();
17
+
18
+ if (USE_THREADS && ! Test2::API::test2_ipc_disabled()) {
19
+ require Test2::IPC;
20
+ require Test2::IPC::Driver::Files;
21
+ Test2::IPC::Driver::Files->import;
22
+ Test2::API::test2_ipc_enable_polling();
23
+ Test2::API::test2_no_wait(1);
24
+ }
25
+ }
26
+
27
+ use Test2::Event::Subtest;
28
+ use Test2::Hub::Subtest;
29
+
30
+ use Test::Builder::Formatter;
31
+ use Test::Builder::TodoDiag;
32
+
33
+ our $Level = 1;
34
+ our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new;
35
+
36
+ sub _add_ts_hooks {
37
+ my $self = shift;
38
+
39
+ my $hub = $self->{Stack}->top;
40
+
41
+ # Take a reference to the hash key, we do this to avoid closing over $self
42
+ # which is the singleton. We use a reference because the value could change
43
+ # in rare cases.
44
+ my $epkgr = \$self->{Exported_To};
45
+
46
+ #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1});
47
+
48
+ $hub->pre_filter(
49
+ sub {
50
+ my ($active_hub, $e) = @_;
51
+
52
+ my $epkg = $$epkgr;
53
+ my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef;
54
+
55
+ no strict 'refs';
56
+ no warnings 'once';
57
+ my $todo;
58
+ $todo = ${"$cpkg\::TODO"} if $cpkg;
59
+ $todo = ${"$epkg\::TODO"} if $epkg && !$todo;
60
+
61
+ return $e unless defined($todo);
62
+ return $e unless length($todo);
63
+
64
+ # Turn a diag into a todo diag
65
+ return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
66
+
67
+ $e->set_todo($todo) if $e->can('set_todo');
68
+ $e->add_amnesty({tag => 'TODO', details => $todo});
69
+
70
+ # Set todo on ok's
71
+ if ($e->isa('Test2::Event::Ok')) {
72
+ $e->set_effective_pass(1);
73
+
74
+ if (my $result = $e->get_meta(__PACKAGE__)) {
75
+ $result->{reason} ||= $todo;
76
+ $result->{type} ||= 'todo';
77
+ $result->{ok} = 1;
78
+ }
79
+ }
80
+
81
+ return $e;
82
+ },
83
+
84
+ inherit => 1,
85
+
86
+ intercept_inherit => {
87
+ clean => sub {
88
+ my %params = @_;
89
+
90
+ my $state = $params{state};
91
+ my $trace = $params{trace};
92
+
93
+ my $epkg = $$epkgr;
94
+ my $cpkg = $trace->{frame}->[0];
95
+
96
+ no strict 'refs';
97
+ no warnings 'once';
98
+
99
+ $state->{+__PACKAGE__} = {};
100
+ $state->{+__PACKAGE__}->{"$cpkg\::TODO"} = ${"$cpkg\::TODO"} if $cpkg;
101
+ $state->{+__PACKAGE__}->{"$epkg\::TODO"} = ${"$epkg\::TODO"} if $epkg;
102
+
103
+ ${"$cpkg\::TODO"} = undef if $cpkg;
104
+ ${"$epkg\::TODO"} = undef if $epkg;
105
+ },
106
+ restore => sub {
107
+ my %params = @_;
108
+ my $state = $params{state};
109
+
110
+ no strict 'refs';
111
+ no warnings 'once';
112
+
113
+ for my $item (keys %{$state->{+__PACKAGE__}}) {
114
+ no strict 'refs';
115
+ no warnings 'once';
116
+
117
+ ${"$item"} = $state->{+__PACKAGE__}->{$item};
118
+ }
119
+ },
120
+ },
121
+ );
122
+ }
123
+
124
+ {
125
+ no warnings;
126
+ INIT {
127
+ use warnings;
128
+ Test2::API::test2_load() unless Test2::API::test2_in_preload();
129
+ }
130
+ }
131
+
132
+ sub new {
133
+ my($class) = shift;
134
+ unless($Test) {
135
+ $Test = $class->create(singleton => 1);
136
+
137
+ Test2::API::test2_add_callback_post_load(
138
+ sub {
139
+ $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0;
140
+ $Test->reset(singleton => 1);
141
+ $Test->_add_ts_hooks;
142
+ }
143
+ );
144
+
145
+ # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So
146
+ # we only want the level to change if $Level != 1.
147
+ # TB->ctx compensates for this later.
148
+ Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 });
149
+
150
+ Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) });
151
+
152
+ Test2::API::test2_ipc()->set_no_fatal(1) if Test2::API::test2_has_ipc();
153
+ }
154
+ return $Test;
155
+ }
156
+
157
+ sub create {
158
+ my $class = shift;
159
+ my %params = @_;
160
+
161
+ my $self = bless {}, $class;
162
+ if ($params{singleton}) {
163
+ $self->{Stack} = Test2::API::test2_stack();
164
+ }
165
+ else {
166
+ $self->{Stack} = Test2::API::Stack->new;
167
+ $self->{Stack}->new_hub(
168
+ formatter => Test::Builder::Formatter->new,
169
+ ipc => Test2::API::test2_ipc(),
170
+ );
171
+
172
+ $self->reset(%params);
173
+ $self->_add_ts_hooks;
174
+ }
175
+
176
+ return $self;
177
+ }
178
+
179
+ sub ctx {
180
+ my $self = shift;
181
+ context(
182
+ # 1 for our frame, another for the -1 off of $Level in our hook at the top.
183
+ level => 2,
184
+ fudge => 1,
185
+ stack => $self->{Stack},
186
+ hub => $self->{Hub},
187
+ wrapped => 1,
188
+ @_
189
+ );
190
+ }
191
+
192
+ sub parent {
193
+ my $self = shift;
194
+ my $ctx = $self->ctx;
195
+ my $chub = $self->{Hub} || $ctx->hub;
196
+ $ctx->release;
197
+
198
+ my $meta = $chub->meta(__PACKAGE__, {});
199
+ my $parent = $meta->{parent};
200
+
201
+ return undef unless $parent;
202
+
203
+ return bless {
204
+ Original_Pid => $$,
205
+ Stack => $self->{Stack},
206
+ Hub => $parent,
207
+ }, blessed($self);
208
+ }
209
+
210
+ sub child {
211
+ my( $self, $name ) = @_;
212
+
213
+ $name ||= "Child of " . $self->name;
214
+ my $ctx = $self->ctx;
215
+
216
+ my $parent = $ctx->hub;
217
+ my $pmeta = $parent->meta(__PACKAGE__, {});
218
+ $self->croak("You already have a child named ($pmeta->{child}) running")
219
+ if $pmeta->{child};
220
+
221
+ $pmeta->{child} = $name;
222
+
223
+ # Clear $TODO for the child.
224
+ my $orig_TODO = $self->find_TODO(undef, 1, undef);
225
+
226
+ my $subevents = [];
227
+
228
+ my $hub = $ctx->stack->new_hub(
229
+ class => 'Test2::Hub::Subtest',
230
+ );
231
+
232
+ $hub->pre_filter(sub {
233
+ my ($active_hub, $e) = @_;
234
+
235
+ # Turn a diag into a todo diag
236
+ return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
237
+
238
+ return $e;
239
+ }, inherit => 1) if $orig_TODO;
240
+
241
+ $hub->listen(sub { push @$subevents => $_[1] });
242
+
243
+ $hub->set_nested( $parent->nested + 1 );
244
+
245
+ my $meta = $hub->meta(__PACKAGE__, {});
246
+ $meta->{Name} = $name;
247
+ $meta->{TODO} = $orig_TODO;
248
+ $meta->{TODO_PKG} = $ctx->trace->package;
249
+ $meta->{parent} = $parent;
250
+ $meta->{Test_Results} = [];
251
+ $meta->{subevents} = $subevents;
252
+ $meta->{subtest_id} = $hub->id;
253
+ $meta->{subtest_uuid} = $hub->uuid;
254
+ $meta->{subtest_buffered} = $parent->format ? 0 : 1;
255
+
256
+ $self->_add_ts_hooks;
257
+
258
+ $ctx->release;
259
+ return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self);
260
+ }
261
+
262
+ sub finalize {
263
+ my $self = shift;
264
+ my $ok = 1;
265
+ ($ok) = @_ if @_;
266
+
267
+ my $st_ctx = $self->ctx;
268
+ my $chub = $self->{Hub} || return $st_ctx->release;
269
+
270
+ my $meta = $chub->meta(__PACKAGE__, {});
271
+ if ($meta->{child}) {
272
+ $self->croak("Can't call finalize() with child ($meta->{child}) active");
273
+ }
274
+
275
+ local $? = 0; # don't fail if $subtests happened to set $? nonzero
276
+
277
+ $self->{Stack}->pop($chub);
278
+
279
+ $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO});
280
+
281
+ my $parent = $self->parent;
282
+ my $ctx = $parent->ctx;
283
+ my $trace = $ctx->trace;
284
+ delete $ctx->hub->meta(__PACKAGE__, {})->{child};
285
+
286
+ $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1)
287
+ if $ok
288
+ && $chub->count
289
+ && !$chub->no_ending
290
+ && !$chub->ended;
291
+
292
+ my $plan = $chub->plan || 0;
293
+ my $count = $chub->count;
294
+ my $failed = $chub->failed;
295
+ my $passed = $chub->is_passing;
296
+
297
+ my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan;
298
+ if ($count && $num_extra != 0) {
299
+ my $s = $plan == 1 ? '' : 's';
300
+ $st_ctx->diag(<<"FAIL");
301
+ Looks like you planned $plan test$s but ran $count.
302
+ FAIL
303
+ }
304
+
305
+ if ($failed) {
306
+ my $s = $failed == 1 ? '' : 's';
307
+
308
+ my $qualifier = $num_extra == 0 ? '' : ' run';
309
+
310
+ $st_ctx->diag(<<"FAIL");
311
+ Looks like you failed $failed test$s of $count$qualifier.
312
+ FAIL
313
+ }
314
+
315
+ if (!$passed && !$failed && $count && !$num_extra) {
316
+ $st_ctx->diag(<<"FAIL");
317
+ All assertions inside the subtest passed, but errors were encountered.
318
+ FAIL
319
+ }
320
+
321
+ $st_ctx->release;
322
+
323
+ unless ($chub->bailed_out) {
324
+ my $plan = $chub->plan;
325
+ if ( $plan && $plan eq 'SKIP' ) {
326
+ $parent->skip($chub->skip_reason, $meta->{Name});
327
+ }
328
+ elsif ( !$chub->count ) {
329
+ $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} );
330
+ }
331
+ else {
332
+ $parent->{subevents} = $meta->{subevents};
333
+ $parent->{subtest_id} = $meta->{subtest_id};
334
+ $parent->{subtest_uuid} = $meta->{subtest_uuid};
335
+ $parent->{subtest_buffered} = $meta->{subtest_buffered};
336
+ $parent->ok( $chub->is_passing, $meta->{Name} );
337
+ }
338
+ }
339
+
340
+ $ctx->release;
341
+ return $chub->is_passing;
342
+ }
343
+
344
+ sub subtest {
345
+ my $self = shift;
346
+ my ($name, $code, @args) = @_;
347
+ my $ctx = $self->ctx;
348
+ $ctx->throw("subtest()'s second argument must be a code ref")
349
+ unless $code && reftype($code) eq 'CODE';
350
+
351
+ $name ||= "Child of " . $self->name;
352
+
353
+
354
+ $_->($name,$code,@args)
355
+ for Test2::API::test2_list_pre_subtest_callbacks();
356
+
357
+ $ctx->note("Subtest: $name");
358
+
359
+ my $child = $self->child($name);
360
+
361
+ my $start_pid = $$;
362
+ my $st_ctx;
363
+ my ($ok, $err, $finished, $child_error);
364
+ T2_SUBTEST_WRAPPER: {
365
+ my $ctx = $self->ctx;
366
+ $st_ctx = $ctx->snapshot;
367
+ $ctx->release;
368
+ $ok = eval { local $Level = 1; $code->(@args); 1 };
369
+ ($err, $child_error) = ($@, $?);
370
+
371
+ # They might have done 'BEGIN { skip_all => "whatever" }'
372
+ if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
373
+ $ok = undef;
374
+ $err = undef;
375
+ }
376
+ else {
377
+ $finished = 1;
378
+ }
379
+ }
380
+
381
+ if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) {
382
+ warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
383
+ exit 255;
384
+ }
385
+
386
+ my $trace = $ctx->trace;
387
+
388
+ if (!$finished) {
389
+ if(my $bailed = $st_ctx->hub->bailed_out) {
390
+ my $chub = $child->{Hub};
391
+ $self->{Stack}->pop($chub);
392
+ $ctx->bail($bailed->reason);
393
+ }
394
+ my $code = $st_ctx->hub->exit_code;
395
+ $ok = !$code;
396
+ $err = "Subtest ended with exit code $code" if $code;
397
+ }
398
+
399
+ my $st_hub = $st_ctx->hub;
400
+ my $plan = $st_hub->plan;
401
+ my $count = $st_hub->count;
402
+
403
+ if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) {
404
+ $st_ctx->plan(0) unless defined $plan;
405
+ $st_ctx->diag('No tests run!');
406
+ }
407
+
408
+ $child->finalize($st_ctx->trace);
409
+
410
+ $ctx->release;
411
+
412
+ die $err unless $ok;
413
+
414
+ $? = $child_error if defined $child_error;
415
+
416
+ return $st_hub->is_passing;
417
+ }
418
+
419
+ sub name {
420
+ my $self = shift;
421
+ my $ctx = $self->ctx;
422
+ release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name};
423
+ }
424
+
425
+ sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
426
+ my ($self, %params) = @_;
427
+
428
+ Test2::API::test2_unset_is_end();
429
+
430
+ # We leave this a global because it has to be localized and localizing
431
+ # hash keys is just asking for pain. Also, it was documented.
432
+ $Level = 1;
433
+
434
+ $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0
435
+ unless $params{singleton};
436
+
437
+ $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$;
438
+
439
+ my $ctx = $self->ctx;
440
+ my $hub = $ctx->hub;
441
+ $ctx->release;
442
+ unless ($params{singleton}) {
443
+ $hub->reset_state();
444
+ $hub->_tb_reset();
445
+ }
446
+
447
+ $ctx = $self->ctx;
448
+
449
+ my $meta = $ctx->hub->meta(__PACKAGE__, {});
450
+ %$meta = (
451
+ Name => $0,
452
+ Ending => 0,
453
+ Done_Testing => undef,
454
+ Skip_All => 0,
455
+ Test_Results => [],
456
+ parent => $meta->{parent},
457
+ );
458
+
459
+ $self->{Exported_To} = undef unless $params{singleton};
460
+
461
+ $self->{Orig_Handles} ||= do {
462
+ my $format = $ctx->hub->format;
463
+ my $out;
464
+ if ($format && $format->isa('Test2::Formatter::TAP')) {
465
+ $out = $format->handles;
466
+ }
467
+ $out ? [@$out] : [];
468
+ };
469
+
470
+ $self->use_numbers(1);
471
+ $self->no_header(0) unless $params{singleton};
472
+ $self->no_ending(0) unless $params{singleton};
473
+ $self->reset_outputs;
474
+
475
+ $ctx->release;
476
+
477
+ return;
478
+ }
479
+
480
+
481
+ my %plan_cmds = (
482
+ no_plan => \&no_plan,
483
+ skip_all => \&skip_all,
484
+ tests => \&_plan_tests,
485
+ );
486
+
487
+ sub plan {
488
+ my( $self, $cmd, $arg ) = @_;
489
+
490
+ return unless $cmd;
491
+
492
+ my $ctx = $self->ctx;
493
+ my $hub = $ctx->hub;
494
+
495
+ $ctx->throw("You tried to plan twice") if $hub->plan;
496
+
497
+ local $Level = $Level + 1;
498
+
499
+ if( my $method = $plan_cmds{$cmd} ) {
500
+ local $Level = $Level + 1;
501
+ $self->$method($arg);
502
+ }
503
+ else {
504
+ my @args = grep { defined } ( $cmd, $arg );
505
+ $ctx->throw("plan() doesn't understand @args");
506
+ }
507
+
508
+ release $ctx, 1;
509
+ }
510
+
511
+
512
+ sub _plan_tests {
513
+ my($self, $arg) = @_;
514
+
515
+ my $ctx = $self->ctx;
516
+
517
+ if($arg) {
518
+ local $Level = $Level + 1;
519
+ $self->expected_tests($arg);
520
+ }
521
+ elsif( !defined $arg ) {
522
+ $ctx->throw("Got an undefined number of tests");
523
+ }
524
+ else {
525
+ $ctx->throw("You said to run 0 tests");
526
+ }
527
+
528
+ $ctx->release;
529
+ }
530
+
531
+
532
+ sub expected_tests {
533
+ my $self = shift;
534
+ my($max) = @_;
535
+
536
+ my $ctx = $self->ctx;
537
+
538
+ if(@_) {
539
+ $self->croak("Number of tests must be a positive integer. You gave it '$max'")
540
+ unless $max =~ /^\+?\d+$/;
541
+
542
+ $ctx->plan($max);
543
+ }
544
+
545
+ my $hub = $ctx->hub;
546
+
547
+ $ctx->release;
548
+
549
+ my $plan = $hub->plan;
550
+ return 0 unless $plan;
551
+ return 0 if $plan =~ m/\D/;
552
+ return $plan;
553
+ }
554
+
555
+
556
+ sub no_plan {
557
+ my($self, $arg) = @_;
558
+
559
+ my $ctx = $self->ctx;
560
+
561
+ if (defined $ctx->hub->plan) {
562
+ warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future.";
563
+ $ctx->release;
564
+ return;
565
+ }
566
+
567
+ $ctx->alert("no_plan takes no arguments") if $arg;
568
+
569
+ $ctx->hub->plan('NO PLAN');
570
+
571
+ release $ctx, 1;
572
+ }
573
+
574
+
575
+ sub done_testing {
576
+ my($self, $num_tests) = @_;
577
+
578
+ my $ctx = $self->ctx;
579
+
580
+ my $meta = $ctx->hub->meta(__PACKAGE__, {});
581
+
582
+ if ($meta->{Done_Testing}) {
583
+ my ($file, $line) = @{$meta->{Done_Testing}}[1,2];
584
+ local $ctx->hub->{ended}; # OMG This is awful.
585
+ $self->ok(0, "done_testing() was already called at $file line $line");
586
+ $ctx->release;
587
+ return;
588
+ }
589
+ $meta->{Done_Testing} = [$ctx->trace->call];
590
+
591
+ my $plan = $ctx->hub->plan;
592
+ my $count = $ctx->hub->count;
593
+
594
+ # If done_testing() specified the number of tests, shut off no_plan
595
+ if( defined $num_tests ) {
596
+ $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN';
597
+ }
598
+ elsif ($count && defined $num_tests && $count != $num_tests) {
599
+ $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests");
600
+ }
601
+ else {
602
+ $num_tests = $self->current_test;
603
+ }
604
+
605
+ if( $self->expected_tests && $num_tests != $self->expected_tests ) {
606
+ $self->ok(0, "planned to run @{[ $self->expected_tests ]} ".
607
+ "but done_testing() expects $num_tests");
608
+ }
609
+
610
+ $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN';
611
+
612
+ $ctx->hub->finalize($ctx->trace, 1);
613
+
614
+ release $ctx, 1;
615
+ }
616
+
617
+
618
+ sub has_plan {
619
+ my $self = shift;
620
+
621
+ my $ctx = $self->ctx;
622
+ my $plan = $ctx->hub->plan;
623
+ $ctx->release;
624
+
625
+ return( $plan ) if $plan && $plan !~ m/\D/;
626
+ return('no_plan') if $plan && $plan eq 'NO PLAN';
627
+ return(undef);
628
+ }
629
+
630
+
631
+ sub skip_all {
632
+ my( $self, $reason ) = @_;
633
+
634
+ my $ctx = $self->ctx;
635
+
636
+ $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1;
637
+
638
+ # Work around old perl bug
639
+ if ($] < 5.020000) {
640
+ my $begin = 0;
641
+ my $level = 0;
642
+ while (my @call = caller($level++)) {
643
+ last unless @call && $call[0];
644
+ next unless $call[3] =~ m/::BEGIN$/;
645
+ $begin++;
646
+ last;
647
+ }
648
+ # HACK!
649
+ die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent};
650
+ }
651
+
652
+ $reason = "$reason" if defined $reason;
653
+
654
+ $ctx->plan(0, SKIP => $reason);
655
+ }
656
+
657
+
658
+ sub exported_to {
659
+ my( $self, $pack ) = @_;
660
+
661
+ if( defined $pack ) {
662
+ $self->{Exported_To} = $pack;
663
+ }
664
+ return $self->{Exported_To};
665
+ }
666
+
667
+
668
+ sub ok {
669
+ my( $self, $test, $name ) = @_;
670
+
671
+ my $ctx = $self->ctx;
672
+
673
+ # $test might contain an object which we don't want to accidentally
674
+ # store, so we turn it into a boolean.
675
+ $test = $test ? 1 : 0;
676
+
677
+ # In case $name is a string overloaded object, force it to stringify.
678
+ no warnings qw/uninitialized numeric/;
679
+ $name = "$name" if defined $name;
680
+
681
+ # Profiling showed that the regex here was a huge time waster, doing the
682
+ # numeric addition first cuts our profile time from ~300ms to ~50ms
683
+ $self->diag(<<" ERR") if 0 + $name && $name =~ /^[\d\s]+$/;
684
+ You named your test '$name'. You shouldn't use numbers for your test names.
685
+ Very confusing.
686
+ ERR
687
+ use warnings qw/uninitialized numeric/;
688
+
689
+ my $trace = $ctx->{trace};
690
+ my $hub = $ctx->{hub};
691
+
692
+ my $result = {
693
+ ok => $test,
694
+ actual_ok => $test,
695
+ reason => '',
696
+ type => '',
697
+ (name => defined($name) ? $name : ''),
698
+ };
699
+
700
+ $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results};
701
+
702
+ my $orig_name = $name;
703
+
704
+ my @attrs;
705
+ my $subevents = delete $self->{subevents};
706
+ my $subtest_id = delete $self->{subtest_id};
707
+ my $subtest_uuid = delete $self->{subtest_uuid};
708
+ my $subtest_buffered = delete $self->{subtest_buffered};
709
+ my $epkg = 'Test2::Event::Ok';
710
+ if ($subevents) {
711
+ $epkg = 'Test2::Event::Subtest';
712
+ push @attrs => (subevents => $subevents, subtest_id => $subtest_id, subtest_uuid => $subtest_uuid, buffered => $subtest_buffered);
713
+ }
714
+
715
+ my $e = bless {
716
+ trace => bless( {%$trace}, 'Test2::EventFacet::Trace'),
717
+ pass => $test,
718
+ name => $name,
719
+ _meta => {'Test::Builder' => $result},
720
+ effective_pass => $test,
721
+ @attrs,
722
+ }, $epkg;
723
+ $hub->send($e);
724
+
725
+ $self->_ok_debug($trace, $orig_name) unless($test);
726
+
727
+ $ctx->release;
728
+ return $test;
729
+ }
730
+
731
+ sub _ok_debug {
732
+ my $self = shift;
733
+ my ($trace, $orig_name) = @_;
734
+
735
+ my $is_todo = $self->in_todo;
736
+
737
+ my $msg = $is_todo ? "Failed (TODO)" : "Failed";
738
+
739
+ my (undef, $file, $line) = $trace->call;
740
+ if (defined $orig_name) {
741
+ $self->diag(qq[ $msg test '$orig_name'\n at $file line $line.\n]);
742
+ }
743
+ else {
744
+ $self->diag(qq[ $msg test at $file line $line.\n]);
745
+ }
746
+ }
747
+
748
+ sub _diag_fh {
749
+ my $self = shift;
750
+ local $Level = $Level + 1;
751
+ return $self->in_todo ? $self->todo_output : $self->failure_output;
752
+ }
753
+
754
+ sub _unoverload {
755
+ my ($self, $type, $thing) = @_;
756
+
757
+ return unless ref $$thing;
758
+ return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') });
759
+ {
760
+ local ($!, $@);
761
+ require overload;
762
+ }
763
+ my $string_meth = overload::Method( $$thing, $type ) || return;
764
+ $$thing = $$thing->$string_meth(undef, 0);
765
+ }
766
+
767
+ sub _unoverload_str {
768
+ my $self = shift;
769
+
770
+ $self->_unoverload( q[""], $_ ) for @_;
771
+ }
772
+
773
+ sub _unoverload_num {
774
+ my $self = shift;
775
+
776
+ $self->_unoverload( '0+', $_ ) for @_;
777
+
778
+ for my $val (@_) {
779
+ next unless $self->_is_dualvar($$val);
780
+ $$val = $$val + 0;
781
+ }
782
+ }
783
+
784
+ # This is a hack to detect a dualvar such as $!
785
+ sub _is_dualvar {
786
+ my( $self, $val ) = @_;
787
+
788
+ # Objects are not dualvars.
789
+ return 0 if ref $val;
790
+
791
+ no warnings 'numeric';
792
+ my $numval = $val + 0;
793
+ return ($numval != 0 and $numval ne $val ? 1 : 0);
794
+ }
795
+
796
+
797
+ sub is_eq {
798
+ my( $self, $got, $expect, $name ) = @_;
799
+
800
+ my $ctx = $self->ctx;
801
+
802
+ local $Level = $Level + 1;
803
+
804
+ if( !defined $got || !defined $expect ) {
805
+ # undef only matches undef and nothing else
806
+ my $test = !defined $got && !defined $expect;
807
+
808
+ $self->ok( $test, $name );
809
+ $self->_is_diag( $got, 'eq', $expect ) unless $test;
810
+ $ctx->release;
811
+ return $test;
812
+ }
813
+
814
+ release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name );
815
+ }
816
+
817
+
818
+ sub is_num {
819
+ my( $self, $got, $expect, $name ) = @_;
820
+ my $ctx = $self->ctx;
821
+ local $Level = $Level + 1;
822
+
823
+ if( !defined $got || !defined $expect ) {
824
+ # undef only matches undef and nothing else
825
+ my $test = !defined $got && !defined $expect;
826
+
827
+ $self->ok( $test, $name );
828
+ $self->_is_diag( $got, '==', $expect ) unless $test;
829
+ $ctx->release;
830
+ return $test;
831
+ }
832
+
833
+ release $ctx, $self->cmp_ok( $got, '==', $expect, $name );
834
+ }
835
+
836
+
837
+ sub _diag_fmt {
838
+ my( $self, $type, $val ) = @_;
839
+
840
+ if( defined $$val ) {
841
+ if( $type eq 'eq' or $type eq 'ne' ) {
842
+ # quote and force string context
843
+ $$val = "'$$val'";
844
+ }
845
+ else {
846
+ # force numeric context
847
+ $self->_unoverload_num($val);
848
+ }
849
+ }
850
+ else {
851
+ $$val = 'undef';
852
+ }
853
+
854
+ return;
855
+ }
856
+
857
+
858
+ sub _is_diag {
859
+ my( $self, $got, $type, $expect ) = @_;
860
+
861
+ $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
862
+
863
+ local $Level = $Level + 1;
864
+ return $self->diag(<<"DIAGNOSTIC");
865
+ got: $got
866
+ expected: $expect
867
+ DIAGNOSTIC
868
+
869
+ }
870
+
871
+ sub _isnt_diag {
872
+ my( $self, $got, $type ) = @_;
873
+
874
+ $self->_diag_fmt( $type, \$got );
875
+
876
+ local $Level = $Level + 1;
877
+ return $self->diag(<<"DIAGNOSTIC");
878
+ got: $got
879
+ expected: anything else
880
+ DIAGNOSTIC
881
+ }
882
+
883
+
884
+ sub isnt_eq {
885
+ my( $self, $got, $dont_expect, $name ) = @_;
886
+ my $ctx = $self->ctx;
887
+ local $Level = $Level + 1;
888
+
889
+ if( !defined $got || !defined $dont_expect ) {
890
+ # undef only matches undef and nothing else
891
+ my $test = defined $got || defined $dont_expect;
892
+
893
+ $self->ok( $test, $name );
894
+ $self->_isnt_diag( $got, 'ne' ) unless $test;
895
+ $ctx->release;
896
+ return $test;
897
+ }
898
+
899
+ release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name );
900
+ }
901
+
902
+ sub isnt_num {
903
+ my( $self, $got, $dont_expect, $name ) = @_;
904
+ my $ctx = $self->ctx;
905
+ local $Level = $Level + 1;
906
+
907
+ if( !defined $got || !defined $dont_expect ) {
908
+ # undef only matches undef and nothing else
909
+ my $test = defined $got || defined $dont_expect;
910
+
911
+ $self->ok( $test, $name );
912
+ $self->_isnt_diag( $got, '!=' ) unless $test;
913
+ $ctx->release;
914
+ return $test;
915
+ }
916
+
917
+ release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name );
918
+ }
919
+
920
+
921
+ sub like {
922
+ my( $self, $thing, $regex, $name ) = @_;
923
+ my $ctx = $self->ctx;
924
+
925
+ local $Level = $Level + 1;
926
+
927
+ release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name );
928
+ }
929
+
930
+ sub unlike {
931
+ my( $self, $thing, $regex, $name ) = @_;
932
+ my $ctx = $self->ctx;
933
+
934
+ local $Level = $Level + 1;
935
+
936
+ release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name );
937
+ }
938
+
939
+
940
+ my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
941
+
942
+ # Bad, these are not comparison operators. Should we include more?
943
+ my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "...");
944
+
945
+ sub cmp_ok {
946
+ my( $self, $got, $type, $expect, $name ) = @_;
947
+ my $ctx = $self->ctx;
948
+
949
+ if ($cmp_ok_bl{$type}) {
950
+ $ctx->throw("$type is not a valid comparison operator in cmp_ok()");
951
+ }
952
+
953
+ my ($test, $succ);
954
+ my $error;
955
+ {
956
+ ## no critic (BuiltinFunctions::ProhibitStringyEval)
957
+
958
+ local( $@, $!, $SIG{__DIE__} ); # isolate eval
959
+
960
+ my($pack, $file, $line) = $ctx->trace->call();
961
+ my $warning_bits = $ctx->trace->warning_bits;
962
+ # convert this to a code string so the BEGIN doesn't have to close
963
+ # over it, which can lead to issues with Devel::Cover
964
+ my $bits_code = defined $warning_bits ? qq["\Q$warning_bits\E"] : 'undef';
965
+
966
+ # Make sure warnings and location matches the caller. Can't do the
967
+ # comparison directly in the eval, as closing over variables can
968
+ # capture them forever when running with Devel::Cover.
969
+ my $check;
970
+ $succ = eval qq[
971
+ BEGIN {\${^WARNING_BITS} = $bits_code};
972
+ #line $line "(eval in cmp_ok) $file"
973
+ \$check = sub { \$_[0] $type \$_[1] };
974
+ 1;
975
+ ];
976
+
977
+ if ($succ) {
978
+ $succ = eval {
979
+ $test = $check->($got, $expect);
980
+ 1;
981
+ };
982
+ }
983
+ $error = $@;
984
+ }
985
+ local $Level = $Level + 1;
986
+ my $ok = $self->ok( $test, $name );
987
+
988
+ # Treat overloaded objects as numbers if we're asked to do a
989
+ # numeric comparison.
990
+ my $unoverload
991
+ = $numeric_cmps{$type}
992
+ ? '_unoverload_num'
993
+ : '_unoverload_str';
994
+
995
+ $self->diag(<<"END") unless $succ;
996
+ An error occurred while using $type:
997
+ ------------------------------------
998
+ $error
999
+ ------------------------------------
1000
+ END
1001
+
1002
+ unless($ok) {
1003
+ $self->$unoverload( \$got, \$expect );
1004
+
1005
+ if( $type =~ /^(eq|==)$/ ) {
1006
+ $self->_is_diag( $got, $type, $expect );
1007
+ }
1008
+ elsif( $type =~ /^(ne|!=)$/ ) {
1009
+ if (defined($got) xor defined($expect)) {
1010
+ $self->_cmp_diag( $got, $type, $expect );
1011
+ }
1012
+ else {
1013
+ $self->_isnt_diag( $got, $type );
1014
+ }
1015
+ }
1016
+ else {
1017
+ $self->_cmp_diag( $got, $type, $expect );
1018
+ }
1019
+ }
1020
+ return release $ctx, $ok;
1021
+ }
1022
+
1023
+ sub _cmp_diag {
1024
+ my( $self, $got, $type, $expect ) = @_;
1025
+
1026
+ $got = defined $got ? "'$got'" : 'undef';
1027
+ $expect = defined $expect ? "'$expect'" : 'undef';
1028
+
1029
+ local $Level = $Level + 1;
1030
+ return $self->diag(<<"DIAGNOSTIC");
1031
+ $got
1032
+ $type
1033
+ $expect
1034
+ DIAGNOSTIC
1035
+ }
1036
+
1037
+ sub _caller_context {
1038
+ my $self = shift;
1039
+
1040
+ my( $pack, $file, $line ) = $self->caller(1);
1041
+
1042
+ my $code = '';
1043
+ $code .= "#line $line $file\n" if defined $file and defined $line;
1044
+
1045
+ return $code;
1046
+ }
1047
+
1048
+
1049
+ sub BAIL_OUT {
1050
+ my( $self, $reason ) = @_;
1051
+
1052
+ my $ctx = $self->ctx;
1053
+
1054
+ $self->{Bailed_Out} = 1;
1055
+
1056
+ $ctx->bail($reason);
1057
+ }
1058
+
1059
+
1060
+ {
1061
+ no warnings 'once';
1062
+ *BAILOUT = \&BAIL_OUT;
1063
+ }
1064
+
1065
+ sub skip {
1066
+ my( $self, $why, $name ) = @_;
1067
+ $why ||= '';
1068
+ $name = '' unless defined $name;
1069
+ $self->_unoverload_str( \$why );
1070
+
1071
+ my $ctx = $self->ctx;
1072
+
1073
+ $name = "$name";
1074
+ $why = "$why";
1075
+
1076
+ $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
1077
+ $name =~ s{\n}{\n# }sg;
1078
+ $why =~ s{\n}{\n# }sg;
1079
+
1080
+ $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1081
+ 'ok' => 1,
1082
+ actual_ok => 1,
1083
+ name => $name,
1084
+ type => 'skip',
1085
+ reason => $why,
1086
+ } unless $self->{no_log_results};
1087
+
1088
+ my $tctx = $ctx->snapshot;
1089
+ $tctx->skip('', $why);
1090
+
1091
+ return release $ctx, 1;
1092
+ }
1093
+
1094
+
1095
+ sub todo_skip {
1096
+ my( $self, $why ) = @_;
1097
+ $why ||= '';
1098
+
1099
+ my $ctx = $self->ctx;
1100
+
1101
+ $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1102
+ 'ok' => 1,
1103
+ actual_ok => 0,
1104
+ name => '',
1105
+ type => 'todo_skip',
1106
+ reason => $why,
1107
+ } unless $self->{no_log_results};
1108
+
1109
+ $why =~ s{\n}{\n# }sg;
1110
+ my $tctx = $ctx->snapshot;
1111
+ $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1112
+
1113
+ return release $ctx, 1;
1114
+ }
1115
+
1116
+
1117
+ sub maybe_regex {
1118
+ my( $self, $regex ) = @_;
1119
+ my $usable_regex = undef;
1120
+
1121
+ return $usable_regex unless defined $regex;
1122
+
1123
+ my( $re, $opts );
1124
+
1125
+ # Check for qr/foo/
1126
+ if( _is_qr($regex) ) {
1127
+ $usable_regex = $regex;
1128
+ }
1129
+ # Check for '/foo/' or 'm,foo,'
1130
+ elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
1131
+ ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1132
+ )
1133
+ {
1134
+ $usable_regex = length $opts ? "(?$opts)$re" : $re;
1135
+ }
1136
+
1137
+ return $usable_regex;
1138
+ }
1139
+
1140
+ sub _is_qr {
1141
+ my $regex = shift;
1142
+
1143
+ # is_regexp() checks for regexes in a robust manner, say if they're
1144
+ # blessed.
1145
+ return re::is_regexp($regex) if defined &re::is_regexp;
1146
+ return ref $regex eq 'Regexp';
1147
+ }
1148
+
1149
+ sub _regex_ok {
1150
+ my( $self, $thing, $regex, $cmp, $name ) = @_;
1151
+
1152
+ my $ok = 0;
1153
+ my $usable_regex = $self->maybe_regex($regex);
1154
+ unless( defined $usable_regex ) {
1155
+ local $Level = $Level + 1;
1156
+ $ok = $self->ok( 0, $name );
1157
+ $self->diag(" '$regex' doesn't look much like a regex to me.");
1158
+ return $ok;
1159
+ }
1160
+
1161
+ {
1162
+ my $test;
1163
+ my $context = $self->_caller_context;
1164
+
1165
+ {
1166
+ ## no critic (BuiltinFunctions::ProhibitStringyEval)
1167
+
1168
+ local( $@, $!, $SIG{__DIE__} ); # isolate eval
1169
+
1170
+ # No point in issuing an uninit warning, they'll see it in the diagnostics
1171
+ no warnings 'uninitialized';
1172
+
1173
+ $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1174
+ }
1175
+
1176
+ $test = !$test if $cmp eq '!~';
1177
+
1178
+ local $Level = $Level + 1;
1179
+ $ok = $self->ok( $test, $name );
1180
+ }
1181
+
1182
+ unless($ok) {
1183
+ $thing = defined $thing ? "'$thing'" : 'undef';
1184
+ my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1185
+
1186
+ local $Level = $Level + 1;
1187
+ $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1188
+ %s
1189
+ %13s '%s'
1190
+ DIAGNOSTIC
1191
+
1192
+ }
1193
+
1194
+ return $ok;
1195
+ }
1196
+
1197
+
1198
+ sub is_fh {
1199
+ my $self = shift;
1200
+ my $maybe_fh = shift;
1201
+ return 0 unless defined $maybe_fh;
1202
+
1203
+ return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1204
+ return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1205
+
1206
+ return eval { $maybe_fh->isa("IO::Handle") } ||
1207
+ eval { tied($maybe_fh)->can('TIEHANDLE') };
1208
+ }
1209
+
1210
+
1211
+ sub level {
1212
+ my( $self, $level ) = @_;
1213
+
1214
+ if( defined $level ) {
1215
+ $Level = $level;
1216
+ }
1217
+ return $Level;
1218
+ }
1219
+
1220
+
1221
+ sub use_numbers {
1222
+ my( $self, $use_nums ) = @_;
1223
+
1224
+ my $ctx = $self->ctx;
1225
+ my $format = $ctx->hub->format;
1226
+ unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
1227
+ warn "The current formatter does not support 'use_numbers'" if $format;
1228
+ return release $ctx, 0;
1229
+ }
1230
+
1231
+ $format->set_no_numbers(!$use_nums) if defined $use_nums;
1232
+
1233
+ return release $ctx, $format->no_numbers ? 0 : 1;
1234
+ }
1235
+
1236
+ BEGIN {
1237
+ for my $method (qw(no_header no_diag)) {
1238
+ my $set = "set_$method";
1239
+ my $code = sub {
1240
+ my( $self, $no ) = @_;
1241
+
1242
+ my $ctx = $self->ctx;
1243
+ my $format = $ctx->hub->format;
1244
+ unless ($format && $format->can($set)) {
1245
+ warn "The current formatter does not support '$method'" if $format;
1246
+ $ctx->release;
1247
+ return
1248
+ }
1249
+
1250
+ $format->$set($no) if defined $no;
1251
+
1252
+ return release $ctx, $format->$method ? 1 : 0;
1253
+ };
1254
+
1255
+ no strict 'refs'; ## no critic
1256
+ *$method = $code;
1257
+ }
1258
+ }
1259
+
1260
+ sub no_ending {
1261
+ my( $self, $no ) = @_;
1262
+
1263
+ my $ctx = $self->ctx;
1264
+
1265
+ $ctx->hub->set_no_ending($no) if defined $no;
1266
+
1267
+ return release $ctx, $ctx->hub->no_ending;
1268
+ }
1269
+
1270
+ sub diag {
1271
+ my $self = shift;
1272
+ return unless @_;
1273
+
1274
+ my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1275
+
1276
+ if (Test2::API::test2_in_preload()) {
1277
+ chomp($text);
1278
+ $text =~ s/^/# /msg;
1279
+ print STDERR $text, "\n";
1280
+ return 0;
1281
+ }
1282
+
1283
+ my $ctx = $self->ctx;
1284
+ $ctx->diag($text);
1285
+ $ctx->release;
1286
+ return 0;
1287
+ }
1288
+
1289
+
1290
+ sub note {
1291
+ my $self = shift;
1292
+ return unless @_;
1293
+
1294
+ my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1295
+
1296
+ if (Test2::API::test2_in_preload()) {
1297
+ chomp($text);
1298
+ $text =~ s/^/# /msg;
1299
+ print STDOUT $text, "\n";
1300
+ return 0;
1301
+ }
1302
+
1303
+ my $ctx = $self->ctx;
1304
+ $ctx->note($text);
1305
+ $ctx->release;
1306
+ return 0;
1307
+ }
1308
+
1309
+
1310
+ sub explain {
1311
+ my $self = shift;
1312
+
1313
+ local ($@, $!);
1314
+ require Data::Dumper;
1315
+
1316
+ return map {
1317
+ ref $_
1318
+ ? do {
1319
+ my $dumper = Data::Dumper->new( [$_] );
1320
+ $dumper->Indent(1)->Terse(1);
1321
+ $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1322
+ $dumper->Dump;
1323
+ }
1324
+ : $_
1325
+ } @_;
1326
+ }
1327
+
1328
+
1329
+ sub output {
1330
+ my( $self, $fh ) = @_;
1331
+
1332
+ my $ctx = $self->ctx;
1333
+ my $format = $ctx->hub->format;
1334
+ $ctx->release;
1335
+ return unless $format && $format->isa('Test2::Formatter::TAP');
1336
+
1337
+ $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1338
+ if defined $fh;
1339
+
1340
+ return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1341
+ }
1342
+
1343
+ sub failure_output {
1344
+ my( $self, $fh ) = @_;
1345
+
1346
+ my $ctx = $self->ctx;
1347
+ my $format = $ctx->hub->format;
1348
+ $ctx->release;
1349
+ return unless $format && $format->isa('Test2::Formatter::TAP');
1350
+
1351
+ $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1352
+ if defined $fh;
1353
+
1354
+ return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1355
+ }
1356
+
1357
+ sub todo_output {
1358
+ my( $self, $fh ) = @_;
1359
+
1360
+ my $ctx = $self->ctx;
1361
+ my $format = $ctx->hub->format;
1362
+ $ctx->release;
1363
+ return unless $format && $format->isa('Test::Builder::Formatter');
1364
+
1365
+ $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1366
+ if defined $fh;
1367
+
1368
+ return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1369
+ }
1370
+
1371
+ sub _new_fh {
1372
+ my $self = shift;
1373
+ my ($file_or_fh) = shift;
1374
+
1375
+ my $fh;
1376
+ if ($self->is_fh($file_or_fh)) {
1377
+ $fh = $file_or_fh;
1378
+ }
1379
+ elsif (ref $file_or_fh eq 'SCALAR') {
1380
+ open $fh, ">>", $file_or_fh
1381
+ or $self->croak("Can't open scalar ref $file_or_fh: $!");
1382
+ }
1383
+ else {
1384
+ open $fh, ">", $file_or_fh
1385
+ or $self->croak("Can't open test output log $file_or_fh: $!");
1386
+ _autoflush($fh);
1387
+ }
1388
+
1389
+ return $fh;
1390
+ }
1391
+
1392
+ sub _autoflush {
1393
+ my($fh) = shift;
1394
+ my $old_fh = select $fh;
1395
+ $| = 1;
1396
+ select $old_fh;
1397
+
1398
+ return;
1399
+ }
1400
+
1401
+
1402
+ sub reset_outputs {
1403
+ my $self = shift;
1404
+
1405
+ my $ctx = $self->ctx;
1406
+ my $format = $ctx->hub->format;
1407
+ $ctx->release;
1408
+ return unless $format && $format->isa('Test2::Formatter::TAP');
1409
+ $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
1410
+
1411
+ return;
1412
+ }
1413
+
1414
+
1415
+ sub carp {
1416
+ my $self = shift;
1417
+ my $ctx = $self->ctx;
1418
+ $ctx->alert(join "", @_);
1419
+ $ctx->release;
1420
+ }
1421
+
1422
+ sub croak {
1423
+ my $self = shift;
1424
+ my $ctx = $self->ctx;
1425
+ $ctx->throw(join "", @_);
1426
+ $ctx->release;
1427
+ }
1428
+
1429
+
1430
+ sub current_test {
1431
+ my( $self, $num ) = @_;
1432
+
1433
+ my $ctx = $self->ctx;
1434
+ my $hub = $ctx->hub;
1435
+
1436
+ if( defined $num ) {
1437
+ $hub->set_count($num);
1438
+
1439
+ unless ($self->{no_log_results}) {
1440
+ # If the test counter is being pushed forward fill in the details.
1441
+ my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1442
+ if ($num > @$test_results) {
1443
+ my $start = @$test_results ? @$test_results : 0;
1444
+ for ($start .. $num - 1) {
1445
+ $test_results->[$_] = {
1446
+ 'ok' => 1,
1447
+ actual_ok => undef,
1448
+ reason => 'incrementing test number',
1449
+ type => 'unknown',
1450
+ name => undef
1451
+ };
1452
+ }
1453
+ }
1454
+ # If backward, wipe history. Its their funeral.
1455
+ elsif ($num < @$test_results) {
1456
+ $#{$test_results} = $num - 1;
1457
+ }
1458
+ }
1459
+ }
1460
+ return release $ctx, $hub->count;
1461
+ }
1462
+
1463
+
1464
+ sub is_passing {
1465
+ my $self = shift;
1466
+
1467
+ my $ctx = $self->ctx;
1468
+ my $hub = $ctx->hub;
1469
+
1470
+ if( @_ ) {
1471
+ my ($bool) = @_;
1472
+ $hub->set_failed(0) if $bool;
1473
+ $hub->is_passing($bool);
1474
+ }
1475
+
1476
+ return release $ctx, $hub->is_passing;
1477
+ }
1478
+
1479
+
1480
+ sub summary {
1481
+ my($self) = shift;
1482
+
1483
+ return if $self->{no_log_results};
1484
+
1485
+ my $ctx = $self->ctx;
1486
+ my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1487
+ $ctx->release;
1488
+ return map { $_ ? $_->{'ok'} : () } @$data;
1489
+ }
1490
+
1491
+
1492
+ sub details {
1493
+ my $self = shift;
1494
+
1495
+ return if $self->{no_log_results};
1496
+
1497
+ my $ctx = $self->ctx;
1498
+ my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1499
+ $ctx->release;
1500
+ return @$data;
1501
+ }
1502
+
1503
+
1504
+ sub find_TODO {
1505
+ my( $self, $pack, $set, $new_value ) = @_;
1506
+
1507
+ my $ctx = $self->ctx;
1508
+
1509
+ $pack ||= $ctx->trace->package || $self->exported_to;
1510
+ $ctx->release;
1511
+
1512
+ return unless $pack;
1513
+
1514
+ no strict 'refs'; ## no critic
1515
+ no warnings 'once';
1516
+ my $old_value = ${ $pack . '::TODO' };
1517
+ $set and ${ $pack . '::TODO' } = $new_value;
1518
+ return $old_value;
1519
+ }
1520
+
1521
+ sub todo {
1522
+ my( $self, $pack ) = @_;
1523
+
1524
+ local $Level = $Level + 1;
1525
+ my $ctx = $self->ctx;
1526
+ $ctx->release;
1527
+
1528
+ my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1529
+ return $meta->[-1]->[1] if $meta && @$meta;
1530
+
1531
+ $pack ||= $ctx->trace->package;
1532
+
1533
+ return unless $pack;
1534
+
1535
+ no strict 'refs'; ## no critic
1536
+ no warnings 'once';
1537
+ return ${ $pack . '::TODO' };
1538
+ }
1539
+
1540
+ sub in_todo {
1541
+ my $self = shift;
1542
+
1543
+ local $Level = $Level + 1;
1544
+ my $ctx = $self->ctx;
1545
+ $ctx->release;
1546
+
1547
+ my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1548
+ return 1 if $meta && @$meta;
1549
+
1550
+ my $pack = $ctx->trace->package || return 0;
1551
+
1552
+ no strict 'refs'; ## no critic
1553
+ no warnings 'once';
1554
+ my $todo = ${ $pack . '::TODO' };
1555
+
1556
+ return 0 unless defined $todo;
1557
+ return 0 if "$todo" eq '';
1558
+ return 1;
1559
+ }
1560
+
1561
+ sub todo_start {
1562
+ my $self = shift;
1563
+ my $message = @_ ? shift : '';
1564
+
1565
+ my $ctx = $self->ctx;
1566
+
1567
+ my $hub = $ctx->hub;
1568
+ my $filter = $hub->pre_filter(sub {
1569
+ my ($active_hub, $e) = @_;
1570
+
1571
+ # Turn a diag into a todo diag
1572
+ return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1573
+
1574
+ # Set todo on ok's
1575
+ if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1576
+ $e->set_todo($message);
1577
+ $e->set_effective_pass(1);
1578
+
1579
+ if (my $result = $e->get_meta(__PACKAGE__)) {
1580
+ $result->{reason} ||= $message;
1581
+ $result->{type} ||= 'todo';
1582
+ $result->{ok} = 1;
1583
+ }
1584
+ }
1585
+
1586
+ return $e;
1587
+ }, inherit => 1);
1588
+
1589
+ push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
1590
+
1591
+ $ctx->release;
1592
+
1593
+ return;
1594
+ }
1595
+
1596
+ sub todo_end {
1597
+ my $self = shift;
1598
+
1599
+ my $ctx = $self->ctx;
1600
+
1601
+ my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
1602
+
1603
+ $ctx->throw('todo_end() called without todo_start()') unless $set;
1604
+
1605
+ $ctx->hub->pre_unfilter($set->[0]);
1606
+
1607
+ $ctx->release;
1608
+
1609
+ return;
1610
+ }
1611
+
1612
+
1613
+ sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1614
+ my( $self ) = @_;
1615
+
1616
+ my $ctx = $self->ctx;
1617
+
1618
+ my $trace = $ctx->trace;
1619
+ $ctx->release;
1620
+ return wantarray ? $trace->call : $trace->package;
1621
+ }
1622
+
1623
+
1624
+ sub _try {
1625
+ my( $self, $code, %opts ) = @_;
1626
+
1627
+ my $error;
1628
+ my $return;
1629
+ {
1630
+ local $!; # eval can mess up $!
1631
+ local $@; # don't set $@ in the test
1632
+ local $SIG{__DIE__}; # don't trip an outside DIE handler.
1633
+ $return = eval { $code->() };
1634
+ $error = $@;
1635
+ }
1636
+
1637
+ die $error if $error and $opts{die_on_fail};
1638
+
1639
+ return wantarray ? ( $return, $error ) : $return;
1640
+ }
1641
+
1642
+ sub _ending {
1643
+ my $self = shift;
1644
+ my ($ctx, $real_exit_code, $new) = @_;
1645
+
1646
+ unless ($ctx) {
1647
+ my $octx = $self->ctx;
1648
+ $ctx = $octx->snapshot;
1649
+ $octx->release;
1650
+ }
1651
+
1652
+ return if $ctx->hub->no_ending;
1653
+ return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1654
+
1655
+ # Don't bother with an ending if this is a forked copy. Only the parent
1656
+ # should do the ending.
1657
+ return unless $self->{Original_Pid} == $$;
1658
+
1659
+ my $hub = $ctx->hub;
1660
+ return if $hub->bailed_out;
1661
+
1662
+ my $plan = $hub->plan;
1663
+ my $count = $hub->count;
1664
+ my $failed = $hub->failed;
1665
+ my $passed = $hub->is_passing;
1666
+ return unless $plan || $count || $failed;
1667
+
1668
+ # Ran tests but never declared a plan or hit done_testing
1669
+ if( !defined($hub->plan) and $hub->count ) {
1670
+ $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1671
+
1672
+ if($real_exit_code) {
1673
+ $self->diag(<<"FAIL");
1674
+ Looks like your test exited with $real_exit_code just after $count.
1675
+ FAIL
1676
+ $$new ||= $real_exit_code;
1677
+ return;
1678
+ }
1679
+
1680
+ # But if the tests ran, handle exit code.
1681
+ if($failed > 0) {
1682
+ my $exit_code = $failed <= 254 ? $failed : 254;
1683
+ $$new ||= $exit_code;
1684
+ return;
1685
+ }
1686
+
1687
+ $$new ||= 254;
1688
+ return;
1689
+ }
1690
+
1691
+ if ($real_exit_code && !$count) {
1692
+ $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1693
+ $$new ||= $real_exit_code;
1694
+ return;
1695
+ }
1696
+
1697
+ return if $plan && "$plan" eq 'SKIP';
1698
+
1699
+ if (!$count) {
1700
+ $self->diag('No tests run!');
1701
+ $$new ||= 255;
1702
+ return;
1703
+ }
1704
+
1705
+ if ($real_exit_code) {
1706
+ $self->diag(<<"FAIL");
1707
+ Looks like your test exited with $real_exit_code just after $count.
1708
+ FAIL
1709
+ $$new ||= $real_exit_code;
1710
+ return;
1711
+ }
1712
+
1713
+ if ($plan eq 'NO PLAN') {
1714
+ $ctx->plan( $count );
1715
+ $plan = $hub->plan;
1716
+ }
1717
+
1718
+ # Figure out if we passed or failed and print helpful messages.
1719
+ my $num_extra = $count - $plan;
1720
+
1721
+ if ($num_extra != 0) {
1722
+ my $s = $plan == 1 ? '' : 's';
1723
+ $self->diag(<<"FAIL");
1724
+ Looks like you planned $plan test$s but ran $count.
1725
+ FAIL
1726
+ }
1727
+
1728
+ if ($failed) {
1729
+ my $s = $failed == 1 ? '' : 's';
1730
+
1731
+ my $qualifier = $num_extra == 0 ? '' : ' run';
1732
+
1733
+ $self->diag(<<"FAIL");
1734
+ Looks like you failed $failed test$s of $count$qualifier.
1735
+ FAIL
1736
+ }
1737
+
1738
+ if (!$passed && !$failed && $count && !$num_extra) {
1739
+ $ctx->diag(<<"FAIL");
1740
+ All assertions passed, but errors were encountered.
1741
+ FAIL
1742
+ }
1743
+
1744
+ my $exit_code = 0;
1745
+ if ($failed) {
1746
+ $exit_code = $failed <= 254 ? $failed : 254;
1747
+ }
1748
+ elsif ($num_extra != 0) {
1749
+ $exit_code = 255;
1750
+ }
1751
+ elsif (!$passed) {
1752
+ $exit_code = 255;
1753
+ }
1754
+
1755
+ $$new ||= $exit_code;
1756
+ return;
1757
+ }
1758
+
1759
+ # Some things used this even though it was private... I am looking at you
1760
+ # Test::Builder::Prefix...
1761
+ sub _print_comment {
1762
+ my( $self, $fh, @msgs ) = @_;
1763
+
1764
+ return if $self->no_diag;
1765
+ return unless @msgs;
1766
+
1767
+ # Prevent printing headers when compiling (i.e. -c)
1768
+ return if $^C;
1769
+
1770
+ # Smash args together like print does.
1771
+ # Convert undef to 'undef' so its readable.
1772
+ my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1773
+
1774
+ # Escape the beginning, _print will take care of the rest.
1775
+ $msg =~ s/^/# /;
1776
+
1777
+ local( $\, $", $, ) = ( undef, ' ', '' );
1778
+ print $fh $msg;
1779
+
1780
+ return 0;
1781
+ }
1782
+
1783
+ # This is used by Test::SharedFork to turn on IPC after the fact. Not
1784
+ # documenting because I do not want it used. The method name is borrowed from
1785
+ # Test::Builder 2
1786
+ # Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1787
+ # will be made smarter.
1788
+ sub coordinate_forks {
1789
+ my $self = shift;
1790
+
1791
+ {
1792
+ local ($@, $!);
1793
+ require Test2::IPC;
1794
+ }
1795
+ Test2::IPC->import;
1796
+ Test2::API::test2_ipc_enable_polling();
1797
+ Test2::API::test2_load();
1798
+ my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1799
+ $ipc->set_no_fatal(1);
1800
+ Test2::API::test2_no_wait(1);
1801
+ }
1802
+
1803
+ sub no_log_results { $_[0]->{no_log_results} = 1 }
1804
+
1805
+ 1;
1806
+
1807
+ __END__
1808
+
1809
+ =head1 NAME
1810
+
1811
+ Test::Builder - Backend for building test libraries
1812
+
1813
+ =head1 SYNOPSIS
1814
+
1815
+ package My::Test::Module;
1816
+ use base 'Test::Builder::Module';
1817
+
1818
+ my $CLASS = __PACKAGE__;
1819
+
1820
+ sub ok {
1821
+ my($test, $name) = @_;
1822
+ my $tb = $CLASS->builder;
1823
+
1824
+ $tb->ok($test, $name);
1825
+ }
1826
+
1827
+
1828
+ =head1 DESCRIPTION
1829
+
1830
+ L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1831
+ but they're not always flexible enough. Test::Builder provides a
1832
+ building block upon which to write your own test libraries I<which can
1833
+ work together>.
1834
+
1835
+ =head2 Construction
1836
+
1837
+ =over 4
1838
+
1839
+ =item B<new>
1840
+
1841
+ my $Test = Test::Builder->new;
1842
+
1843
+ Returns a Test::Builder object representing the current state of the
1844
+ test.
1845
+
1846
+ Since you only run one test per program C<new> always returns the same
1847
+ Test::Builder object. No matter how many times you call C<new()>, you're
1848
+ getting the same object. This is called a singleton. This is done so that
1849
+ multiple modules share such global information as the test counter and
1850
+ where test output is going.
1851
+
1852
+ If you want a completely new Test::Builder object different from the
1853
+ singleton, use C<create>.
1854
+
1855
+ =item B<create>
1856
+
1857
+ my $Test = Test::Builder->create;
1858
+
1859
+ Ok, so there can be more than one Test::Builder object and this is how
1860
+ you get it. You might use this instead of C<new()> if you're testing
1861
+ a Test::Builder based module, but otherwise you probably want C<new>.
1862
+
1863
+ B<NOTE>: the implementation is not complete. C<level>, for example, is still
1864
+ shared by B<all> Test::Builder objects, even ones created using this method.
1865
+ Also, the method name may change in the future.
1866
+
1867
+ =item B<subtest>
1868
+
1869
+ $builder->subtest($name, \&subtests, @args);
1870
+
1871
+ See documentation of C<subtest> in Test::More.
1872
+
1873
+ C<subtest> also, and optionally, accepts arguments which will be passed to the
1874
+ subtests reference.
1875
+
1876
+ =item B<name>
1877
+
1878
+ diag $builder->name;
1879
+
1880
+ Returns the name of the current builder. Top level builders default to C<$0>
1881
+ (the name of the executable). Child builders are named via the C<child>
1882
+ method. If no name is supplied, will be named "Child of $parent->name".
1883
+
1884
+ =item B<reset>
1885
+
1886
+ $Test->reset;
1887
+
1888
+ Reinitializes the Test::Builder singleton to its original state.
1889
+ Mostly useful for tests run in persistent environments where the same
1890
+ test might be run multiple times in the same process.
1891
+
1892
+ =back
1893
+
1894
+ =head2 Setting up tests
1895
+
1896
+ These methods are for setting up tests and declaring how many there
1897
+ are. You usually only want to call one of these methods.
1898
+
1899
+ =over 4
1900
+
1901
+ =item B<plan>
1902
+
1903
+ $Test->plan('no_plan');
1904
+ $Test->plan( skip_all => $reason );
1905
+ $Test->plan( tests => $num_tests );
1906
+
1907
+ A convenient way to set up your tests. Call this and Test::Builder
1908
+ will print the appropriate headers and take the appropriate actions.
1909
+
1910
+ If you call C<plan()>, don't call any of the other methods below.
1911
+
1912
+ =item B<expected_tests>
1913
+
1914
+ my $max = $Test->expected_tests;
1915
+ $Test->expected_tests($max);
1916
+
1917
+ Gets/sets the number of tests we expect this test to run and prints out
1918
+ the appropriate headers.
1919
+
1920
+
1921
+ =item B<no_plan>
1922
+
1923
+ $Test->no_plan;
1924
+
1925
+ Declares that this test will run an indeterminate number of tests.
1926
+
1927
+
1928
+ =item B<done_testing>
1929
+
1930
+ $Test->done_testing();
1931
+ $Test->done_testing($num_tests);
1932
+
1933
+ Declares that you are done testing, no more tests will be run after this point.
1934
+
1935
+ If a plan has not yet been output, it will do so.
1936
+
1937
+ $num_tests is the number of tests you planned to run. If a numbered
1938
+ plan was already declared, and if this contradicts, a failing test
1939
+ will be run to reflect the planning mistake. If C<no_plan> was declared,
1940
+ this will override.
1941
+
1942
+ If C<done_testing()> is called twice, the second call will issue a
1943
+ failing test.
1944
+
1945
+ If C<$num_tests> is omitted, the number of tests run will be used, like
1946
+ no_plan.
1947
+
1948
+ C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1949
+ safer. You'd use it like so:
1950
+
1951
+ $Test->ok($a == $b);
1952
+ $Test->done_testing();
1953
+
1954
+ Or to plan a variable number of tests:
1955
+
1956
+ for my $test (@tests) {
1957
+ $Test->ok($test);
1958
+ }
1959
+ $Test->done_testing(scalar @tests);
1960
+
1961
+
1962
+ =item B<has_plan>
1963
+
1964
+ $plan = $Test->has_plan
1965
+
1966
+ Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1967
+ has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1968
+ of expected tests).
1969
+
1970
+ =item B<skip_all>
1971
+
1972
+ $Test->skip_all;
1973
+ $Test->skip_all($reason);
1974
+
1975
+ Skips all the tests, using the given C<$reason>. Exits immediately with 0.
1976
+
1977
+ =item B<exported_to>
1978
+
1979
+ my $pack = $Test->exported_to;
1980
+ $Test->exported_to($pack);
1981
+
1982
+ Tells Test::Builder what package you exported your functions to.
1983
+
1984
+ This method isn't terribly useful since modules which share the same
1985
+ Test::Builder object might get exported to different packages and only
1986
+ the last one will be honored.
1987
+
1988
+ =back
1989
+
1990
+ =head2 Running tests
1991
+
1992
+ These actually run the tests, analogous to the functions in Test::More.
1993
+
1994
+ They all return true if the test passed, false if the test failed.
1995
+
1996
+ C<$name> is always optional.
1997
+
1998
+ =over 4
1999
+
2000
+ =item B<ok>
2001
+
2002
+ $Test->ok($test, $name);
2003
+
2004
+ Your basic test. Pass if C<$test> is true, fail if $test is false. Just
2005
+ like Test::Simple's C<ok()>.
2006
+
2007
+ =item B<is_eq>
2008
+
2009
+ $Test->is_eq($got, $expected, $name);
2010
+
2011
+ Like Test::More's C<is()>. Checks if C<$got eq $expected>. This is the
2012
+ string version.
2013
+
2014
+ C<undef> only ever matches another C<undef>.
2015
+
2016
+ =item B<is_num>
2017
+
2018
+ $Test->is_num($got, $expected, $name);
2019
+
2020
+ Like Test::More's C<is()>. Checks if C<$got == $expected>. This is the
2021
+ numeric version.
2022
+
2023
+ C<undef> only ever matches another C<undef>.
2024
+
2025
+ =item B<isnt_eq>
2026
+
2027
+ $Test->isnt_eq($got, $dont_expect, $name);
2028
+
2029
+ Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2030
+ the string version.
2031
+
2032
+ =item B<isnt_num>
2033
+
2034
+ $Test->isnt_num($got, $dont_expect, $name);
2035
+
2036
+ Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2037
+ the numeric version.
2038
+
2039
+ =item B<like>
2040
+
2041
+ $Test->like($thing, qr/$regex/, $name);
2042
+ $Test->like($thing, '/$regex/', $name);
2043
+
2044
+ Like L<Test::More>'s C<like()>. Checks if $thing matches the given C<$regex>.
2045
+
2046
+ =item B<unlike>
2047
+
2048
+ $Test->unlike($thing, qr/$regex/, $name);
2049
+ $Test->unlike($thing, '/$regex/', $name);
2050
+
2051
+ Like L<Test::More>'s C<unlike()>. Checks if $thing B<does not match> the
2052
+ given C<$regex>.
2053
+
2054
+ =item B<cmp_ok>
2055
+
2056
+ $Test->cmp_ok($thing, $type, $that, $name);
2057
+
2058
+ Works just like L<Test::More>'s C<cmp_ok()>.
2059
+
2060
+ $Test->cmp_ok($big_num, '!=', $other_big_num);
2061
+
2062
+ =back
2063
+
2064
+ =head2 Other Testing Methods
2065
+
2066
+ These are methods which are used in the course of writing a test but are not themselves tests.
2067
+
2068
+ =over 4
2069
+
2070
+ =item B<BAIL_OUT>
2071
+
2072
+ $Test->BAIL_OUT($reason);
2073
+
2074
+ Indicates to the L<Test::Harness> that things are going so badly all
2075
+ testing should terminate. This includes running any additional test
2076
+ scripts.
2077
+
2078
+ It will exit with 255.
2079
+
2080
+ =for deprecated
2081
+ BAIL_OUT() used to be BAILOUT()
2082
+
2083
+ =item B<skip>
2084
+
2085
+ $Test->skip;
2086
+ $Test->skip($why);
2087
+
2088
+ Skips the current test, reporting C<$why>.
2089
+
2090
+ =item B<todo_skip>
2091
+
2092
+ $Test->todo_skip;
2093
+ $Test->todo_skip($why);
2094
+
2095
+ Like C<skip()>, only it will declare the test as failing and TODO. Similar
2096
+ to
2097
+
2098
+ print "not ok $tnum # TODO $why\n";
2099
+
2100
+ =begin _unimplemented
2101
+
2102
+ =item B<skip_rest>
2103
+
2104
+ $Test->skip_rest;
2105
+ $Test->skip_rest($reason);
2106
+
2107
+ Like C<skip()>, only it skips all the rest of the tests you plan to run
2108
+ and terminates the test.
2109
+
2110
+ If you're running under C<no_plan>, it skips once and terminates the
2111
+ test.
2112
+
2113
+ =end _unimplemented
2114
+
2115
+ =back
2116
+
2117
+
2118
+ =head2 Test building utility methods
2119
+
2120
+ These methods are useful when writing your own test methods.
2121
+
2122
+ =over 4
2123
+
2124
+ =item B<maybe_regex>
2125
+
2126
+ $Test->maybe_regex(qr/$regex/);
2127
+ $Test->maybe_regex('/$regex/');
2128
+
2129
+ This method used to be useful back when Test::Builder worked on Perls
2130
+ before 5.6 which didn't have qr//. Now its pretty useless.
2131
+
2132
+ Convenience method for building testing functions that take regular
2133
+ expressions as arguments.
2134
+
2135
+ Takes a quoted regular expression produced by C<qr//>, or a string
2136
+ representing a regular expression.
2137
+
2138
+ Returns a Perl value which may be used instead of the corresponding
2139
+ regular expression, or C<undef> if its argument is not recognized.
2140
+
2141
+ For example, a version of C<like()>, sans the useful diagnostic messages,
2142
+ could be written as:
2143
+
2144
+ sub laconic_like {
2145
+ my ($self, $thing, $regex, $name) = @_;
2146
+ my $usable_regex = $self->maybe_regex($regex);
2147
+ die "expecting regex, found '$regex'\n"
2148
+ unless $usable_regex;
2149
+ $self->ok($thing =~ m/$usable_regex/, $name);
2150
+ }
2151
+
2152
+
2153
+ =item B<is_fh>
2154
+
2155
+ my $is_fh = $Test->is_fh($thing);
2156
+
2157
+ Determines if the given C<$thing> can be used as a filehandle.
2158
+
2159
+ =cut
2160
+
2161
+
2162
+ =back
2163
+
2164
+
2165
+ =head2 Test style
2166
+
2167
+
2168
+ =over 4
2169
+
2170
+ =item B<level>
2171
+
2172
+ $Test->level($how_high);
2173
+
2174
+ How far up the call stack should C<$Test> look when reporting where the
2175
+ test failed.
2176
+
2177
+ Defaults to 1.
2178
+
2179
+ Setting C<$Test::Builder::Level> overrides. This is typically useful
2180
+ localized:
2181
+
2182
+ sub my_ok {
2183
+ my $test = shift;
2184
+
2185
+ local $Test::Builder::Level = $Test::Builder::Level + 1;
2186
+ $TB->ok($test);
2187
+ }
2188
+
2189
+ To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2190
+
2191
+ =item B<use_numbers>
2192
+
2193
+ $Test->use_numbers($on_or_off);
2194
+
2195
+ Whether or not the test should output numbers. That is, this if true:
2196
+
2197
+ ok 1
2198
+ ok 2
2199
+ ok 3
2200
+
2201
+ or this if false
2202
+
2203
+ ok
2204
+ ok
2205
+ ok
2206
+
2207
+ Most useful when you can't depend on the test output order, such as
2208
+ when threads or forking is involved.
2209
+
2210
+ Defaults to on.
2211
+
2212
+ =item B<no_diag>
2213
+
2214
+ $Test->no_diag($no_diag);
2215
+
2216
+ If set true no diagnostics will be printed. This includes calls to
2217
+ C<diag()>.
2218
+
2219
+ =item B<no_ending>
2220
+
2221
+ $Test->no_ending($no_ending);
2222
+
2223
+ Normally, Test::Builder does some extra diagnostics when the test
2224
+ ends. It also changes the exit code as described below.
2225
+
2226
+ If this is true, none of that will be done.
2227
+
2228
+ =item B<no_header>
2229
+
2230
+ $Test->no_header($no_header);
2231
+
2232
+ If set to true, no "1..N" header will be printed.
2233
+
2234
+ =back
2235
+
2236
+ =head2 Output
2237
+
2238
+ Controlling where the test output goes.
2239
+
2240
+ It's ok for your test to change where STDOUT and STDERR point to,
2241
+ Test::Builder's default output settings will not be affected.
2242
+
2243
+ =over 4
2244
+
2245
+ =item B<diag>
2246
+
2247
+ $Test->diag(@msgs);
2248
+
2249
+ Prints out the given C<@msgs>. Like C<print>, arguments are simply
2250
+ appended together.
2251
+
2252
+ Normally, it uses the C<failure_output()> handle, but if this is for a
2253
+ TODO test, the C<todo_output()> handle is used.
2254
+
2255
+ Output will be indented and marked with a # so as not to interfere
2256
+ with test output. A newline will be put on the end if there isn't one
2257
+ already.
2258
+
2259
+ We encourage using this rather than calling print directly.
2260
+
2261
+ Returns false. Why? Because C<diag()> is often used in conjunction with
2262
+ a failing test (C<ok() || diag()>) it "passes through" the failure.
2263
+
2264
+ return ok(...) || diag(...);
2265
+
2266
+ =for blame transfer
2267
+ Mark Fowler <mark@twoshortplanks.com>
2268
+
2269
+ =item B<note>
2270
+
2271
+ $Test->note(@msgs);
2272
+
2273
+ Like C<diag()>, but it prints to the C<output()> handle so it will not
2274
+ normally be seen by the user except in verbose mode.
2275
+
2276
+ =item B<explain>
2277
+
2278
+ my @dump = $Test->explain(@msgs);
2279
+
2280
+ Will dump the contents of any references in a human readable format.
2281
+ Handy for things like...
2282
+
2283
+ is_deeply($have, $want) || diag explain $have;
2284
+
2285
+ or
2286
+
2287
+ is_deeply($have, $want) || note explain $have;
2288
+
2289
+ =item B<output>
2290
+
2291
+ =item B<failure_output>
2292
+
2293
+ =item B<todo_output>
2294
+
2295
+ my $filehandle = $Test->output;
2296
+ $Test->output($filehandle);
2297
+ $Test->output($filename);
2298
+ $Test->output(\$scalar);
2299
+
2300
+ These methods control where Test::Builder will print its output.
2301
+ They take either an open C<$filehandle>, a C<$filename> to open and write to
2302
+ or a C<$scalar> reference to append to. It will always return a C<$filehandle>.
2303
+
2304
+ B<output> is where normal "ok/not ok" test output goes.
2305
+
2306
+ Defaults to STDOUT.
2307
+
2308
+ B<failure_output> is where diagnostic output on test failures and
2309
+ C<diag()> goes. It is normally not read by Test::Harness and instead is
2310
+ displayed to the user.
2311
+
2312
+ Defaults to STDERR.
2313
+
2314
+ C<todo_output> is used instead of C<failure_output()> for the
2315
+ diagnostics of a failing TODO test. These will not be seen by the
2316
+ user.
2317
+
2318
+ Defaults to STDOUT.
2319
+
2320
+ =item reset_outputs
2321
+
2322
+ $tb->reset_outputs;
2323
+
2324
+ Resets all the output filehandles back to their defaults.
2325
+
2326
+ =item carp
2327
+
2328
+ $tb->carp(@message);
2329
+
2330
+ Warns with C<@message> but the message will appear to come from the
2331
+ point where the original test function was called (C<< $tb->caller >>).
2332
+
2333
+ =item croak
2334
+
2335
+ $tb->croak(@message);
2336
+
2337
+ Dies with C<@message> but the message will appear to come from the
2338
+ point where the original test function was called (C<< $tb->caller >>).
2339
+
2340
+
2341
+ =back
2342
+
2343
+
2344
+ =head2 Test Status and Info
2345
+
2346
+ =over 4
2347
+
2348
+ =item B<no_log_results>
2349
+
2350
+ This will turn off result long-term storage. Calling this method will make
2351
+ C<details> and C<summary> useless. You may want to use this if you are running
2352
+ enough tests to fill up all available memory.
2353
+
2354
+ Test::Builder->new->no_log_results();
2355
+
2356
+ There is no way to turn it back on.
2357
+
2358
+ =item B<current_test>
2359
+
2360
+ my $curr_test = $Test->current_test;
2361
+ $Test->current_test($num);
2362
+
2363
+ Gets/sets the current test number we're on. You usually shouldn't
2364
+ have to set this.
2365
+
2366
+ If set forward, the details of the missing tests are filled in as 'unknown'.
2367
+ if set backward, the details of the intervening tests are deleted. You
2368
+ can erase history if you really want to.
2369
+
2370
+
2371
+ =item B<is_passing>
2372
+
2373
+ my $ok = $builder->is_passing;
2374
+
2375
+ Indicates if the test suite is currently passing.
2376
+
2377
+ More formally, it will be false if anything has happened which makes
2378
+ it impossible for the test suite to pass. True otherwise.
2379
+
2380
+ For example, if no tests have run C<is_passing()> will be true because
2381
+ even though a suite with no tests is a failure you can add a passing
2382
+ test to it and start passing.
2383
+
2384
+ Don't think about it too much.
2385
+
2386
+
2387
+ =item B<summary>
2388
+
2389
+ my @tests = $Test->summary;
2390
+
2391
+ A simple summary of the tests so far. True for pass, false for fail.
2392
+ This is a logical pass/fail, so todos are passes.
2393
+
2394
+ Of course, test #1 is $tests[0], etc...
2395
+
2396
+
2397
+ =item B<details>
2398
+
2399
+ my @tests = $Test->details;
2400
+
2401
+ Like C<summary()>, but with a lot more detail.
2402
+
2403
+ $tests[$test_num - 1] =
2404
+ { 'ok' => is the test considered a pass?
2405
+ actual_ok => did it literally say 'ok'?
2406
+ name => name of the test (if any)
2407
+ type => type of test (if any, see below).
2408
+ reason => reason for the above (if any)
2409
+ };
2410
+
2411
+ 'ok' is true if Test::Harness will consider the test to be a pass.
2412
+
2413
+ 'actual_ok' is a reflection of whether or not the test literally
2414
+ printed 'ok' or 'not ok'. This is for examining the result of 'todo'
2415
+ tests.
2416
+
2417
+ 'name' is the name of the test.
2418
+
2419
+ 'type' indicates if it was a special test. Normal tests have a type
2420
+ of ''. Type can be one of the following:
2421
+
2422
+ skip see skip()
2423
+ todo see todo()
2424
+ todo_skip see todo_skip()
2425
+ unknown see below
2426
+
2427
+ Sometimes the Test::Builder test counter is incremented without it
2428
+ printing any test output, for example, when C<current_test()> is changed.
2429
+ In these cases, Test::Builder doesn't know the result of the test, so
2430
+ its type is 'unknown'. These details for these tests are filled in.
2431
+ They are considered ok, but the name and actual_ok is left C<undef>.
2432
+
2433
+ For example "not ok 23 - hole count # TODO insufficient donuts" would
2434
+ result in this structure:
2435
+
2436
+ $tests[22] = # 23 - 1, since arrays start from 0.
2437
+ { ok => 1, # logically, the test passed since its todo
2438
+ actual_ok => 0, # in absolute terms, it failed
2439
+ name => 'hole count',
2440
+ type => 'todo',
2441
+ reason => 'insufficient donuts'
2442
+ };
2443
+
2444
+
2445
+ =item B<todo>
2446
+
2447
+ my $todo_reason = $Test->todo;
2448
+ my $todo_reason = $Test->todo($pack);
2449
+
2450
+ If the current tests are considered "TODO" it will return the reason,
2451
+ if any. This reason can come from a C<$TODO> variable or the last call
2452
+ to C<todo_start()>.
2453
+
2454
+ Since a TODO test does not need a reason, this function can return an
2455
+ empty string even when inside a TODO block. Use C<< $Test->in_todo >>
2456
+ to determine if you are currently inside a TODO block.
2457
+
2458
+ C<todo()> is about finding the right package to look for C<$TODO> in. It's
2459
+ pretty good at guessing the right package to look at. It first looks for
2460
+ the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2461
+ a test function. As a last resort it will use C<exported_to()>.
2462
+
2463
+ Sometimes there is some confusion about where C<todo()> should be looking
2464
+ for the C<$TODO> variable. If you want to be sure, tell it explicitly
2465
+ what $pack to use.
2466
+
2467
+ =item B<find_TODO>
2468
+
2469
+ my $todo_reason = $Test->find_TODO();
2470
+ my $todo_reason = $Test->find_TODO($pack);
2471
+
2472
+ Like C<todo()> but only returns the value of C<$TODO> ignoring
2473
+ C<todo_start()>.
2474
+
2475
+ Can also be used to set C<$TODO> to a new value while returning the
2476
+ old value:
2477
+
2478
+ my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2479
+
2480
+ =item B<in_todo>
2481
+
2482
+ my $in_todo = $Test->in_todo;
2483
+
2484
+ Returns true if the test is currently inside a TODO block.
2485
+
2486
+ =item B<todo_start>
2487
+
2488
+ $Test->todo_start();
2489
+ $Test->todo_start($message);
2490
+
2491
+ This method allows you declare all subsequent tests as TODO tests, up until
2492
+ the C<todo_end> method has been called.
2493
+
2494
+ The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2495
+ whether or not we're in a TODO test. However, often we find that this is not
2496
+ possible to determine (such as when we want to use C<$TODO> but
2497
+ the tests are being executed in other packages which can't be inferred
2498
+ beforehand).
2499
+
2500
+ Note that you can use this to nest "todo" tests
2501
+
2502
+ $Test->todo_start('working on this');
2503
+ # lots of code
2504
+ $Test->todo_start('working on that');
2505
+ # more code
2506
+ $Test->todo_end;
2507
+ $Test->todo_end;
2508
+
2509
+ This is generally not recommended, but large testing systems often have weird
2510
+ internal needs.
2511
+
2512
+ We've tried to make this also work with the TODO: syntax, but it's not
2513
+ guaranteed and its use is also discouraged:
2514
+
2515
+ TODO: {
2516
+ local $TODO = 'We have work to do!';
2517
+ $Test->todo_start('working on this');
2518
+ # lots of code
2519
+ $Test->todo_start('working on that');
2520
+ # more code
2521
+ $Test->todo_end;
2522
+ $Test->todo_end;
2523
+ }
2524
+
2525
+ Pick one style or another of "TODO" to be on the safe side.
2526
+
2527
+
2528
+ =item C<todo_end>
2529
+
2530
+ $Test->todo_end;
2531
+
2532
+ Stops running tests as "TODO" tests. This method is fatal if called without a
2533
+ preceding C<todo_start> method call.
2534
+
2535
+ =item B<caller>
2536
+
2537
+ my $package = $Test->caller;
2538
+ my($pack, $file, $line) = $Test->caller;
2539
+ my($pack, $file, $line) = $Test->caller($height);
2540
+
2541
+ Like the normal C<caller()>, except it reports according to your C<level()>.
2542
+
2543
+ C<$height> will be added to the C<level()>.
2544
+
2545
+ If C<caller()> winds up off the top of the stack it report the highest context.
2546
+
2547
+ =back
2548
+
2549
+ =head1 EXIT CODES
2550
+
2551
+ If all your tests passed, Test::Builder will exit with zero (which is
2552
+ normal). If anything failed it will exit with how many failed. If
2553
+ you run less (or more) tests than you planned, the missing (or extras)
2554
+ will be considered failures. If no tests were ever run Test::Builder
2555
+ will throw a warning and exit with 255. If the test died, even after
2556
+ having successfully completed all its tests, it will still be
2557
+ considered a failure and will exit with 255.
2558
+
2559
+ So the exit codes are...
2560
+
2561
+ 0 all tests successful
2562
+ 255 test died or all passed but wrong # of tests run
2563
+ any other number how many failed (including missing or extras)
2564
+
2565
+ If you fail more than 254 tests, it will be reported as 254.
2566
+
2567
+ =head1 THREADS
2568
+
2569
+ In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is
2570
+ shared by all threads. This means if one thread sets the test number using
2571
+ C<current_test()> they will all be affected.
2572
+
2573
+ While versions earlier than 5.8.1 had threads they contain too many
2574
+ bugs to support.
2575
+
2576
+ Test::Builder is only thread-aware if threads.pm is loaded I<before>
2577
+ Test::Builder.
2578
+
2579
+ You can directly disable thread support with one of the following:
2580
+
2581
+ $ENV{T2_NO_IPC} = 1
2582
+
2583
+ or
2584
+
2585
+ no Test2::IPC;
2586
+
2587
+ or
2588
+
2589
+ Test2::API::test2_ipc_disable()
2590
+
2591
+ =head1 MEMORY
2592
+
2593
+ An informative hash, accessible via C<details()>, is stored for each
2594
+ test you perform. So memory usage will scale linearly with each test
2595
+ run. Although this is not a problem for most test suites, it can
2596
+ become an issue if you do large (hundred thousands to million)
2597
+ combinatorics tests in the same run.
2598
+
2599
+ In such cases, you are advised to either split the test file into smaller
2600
+ ones, or use a reverse approach, doing "normal" (code) compares and
2601
+ triggering C<fail()> should anything go unexpected.
2602
+
2603
+ Future versions of Test::Builder will have a way to turn history off.
2604
+
2605
+
2606
+ =head1 EXAMPLES
2607
+
2608
+ CPAN can provide the best examples. L<Test::Simple>, L<Test::More>,
2609
+ L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2610
+
2611
+ =head1 SEE ALSO
2612
+
2613
+ =head2 INTERNALS
2614
+
2615
+ L<Test2>, L<Test2::API>
2616
+
2617
+ =head2 LEGACY
2618
+
2619
+ L<Test::Simple>, L<Test::More>
2620
+
2621
+ =head2 EXTERNAL
2622
+
2623
+ L<Test::Harness>
2624
+
2625
+ =head1 AUTHORS
2626
+
2627
+ Original code by chromatic, maintained by Michael G Schwern
2628
+ E<lt>schwern@pobox.comE<gt>
2629
+
2630
+ =head1 MAINTAINERS
2631
+
2632
+ =over 4
2633
+
2634
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2635
+
2636
+ =back
2637
+
2638
+ =head1 COPYRIGHT
2639
+
2640
+ Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2641
+ Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2642
+
2643
+ This program is free software; you can redistribute it and/or
2644
+ modify it under the same terms as Perl itself.
2645
+
2646
+ See L<https://dev.perl.org/licenses/>
git/usr/share/perl5/core_perl/Test/Harness.pm ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test::Harness;
2
+
3
+ use 5.006;
4
+
5
+ use strict;
6
+ use warnings;
7
+
8
+ use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ );
9
+ use constant IS_VMS => ( $^O eq 'VMS' );
10
+
11
+ use TAP::Harness ();
12
+ use TAP::Parser::Aggregator ();
13
+ use TAP::Parser::Source ();
14
+ use TAP::Parser::SourceHandler::Perl ();
15
+
16
+ use Text::ParseWords qw(shellwords);
17
+
18
+ use Config;
19
+ use base 'Exporter';
20
+
21
+ # $ML $Last_ML_Print
22
+
23
+ BEGIN {
24
+ eval q{use Time::HiRes 'time'};
25
+ our $has_time_hires = !$@;
26
+ }
27
+
28
+ =head1 NAME
29
+
30
+ Test::Harness - Run Perl standard test scripts with statistics
31
+
32
+ =head1 VERSION
33
+
34
+ Version 3.50
35
+
36
+ =cut
37
+
38
+ our $VERSION = '3.50';
39
+
40
+ # Backwards compatibility for exportable variable names.
41
+ *verbose = *Verbose;
42
+ *switches = *Switches;
43
+ *debug = *Debug;
44
+
45
+ $ENV{HARNESS_ACTIVE} = 1;
46
+ $ENV{HARNESS_VERSION} = $VERSION;
47
+
48
+ END {
49
+
50
+ # For VMS.
51
+ delete $ENV{HARNESS_ACTIVE};
52
+ delete $ENV{HARNESS_VERSION};
53
+ }
54
+
55
+ our @EXPORT = qw(&runtests);
56
+ our @EXPORT_OK = qw(&execute_tests $verbose $switches);
57
+
58
+ our $Verbose = $ENV{HARNESS_VERBOSE} || 0;
59
+ our $Debug = $ENV{HARNESS_DEBUG} || 0;
60
+ our $Switches = '-w';
61
+ our $Columns = $ENV{HARNESS_COLUMNS} || $ENV{COLUMNS} || 80;
62
+ $Columns--; # Some shells have trouble with a full line of text.
63
+ our $Timer = $ENV{HARNESS_TIMER} || 0;
64
+ our $Color = $ENV{HARNESS_COLOR} || 0;
65
+ our $IgnoreExit = $ENV{HARNESS_IGNORE_EXIT} || 0;
66
+
67
+ =head1 SYNOPSIS
68
+
69
+ use Test::Harness;
70
+
71
+ runtests(@test_files);
72
+
73
+ =head1 DESCRIPTION
74
+
75
+ Although, for historical reasons, the L<Test::Harness> distribution
76
+ takes its name from this module it now exists only to provide
77
+ L<TAP::Harness> with an interface that is somewhat backwards compatible
78
+ with L<Test::Harness> 2.xx. If you're writing new code consider using
79
+ L<TAP::Harness> directly instead.
80
+
81
+ Emulation is provided for C<runtests> and C<execute_tests> but the
82
+ pluggable 'Straps' interface that previous versions of L<Test::Harness>
83
+ supported is not reproduced here. Straps is now available as a stand
84
+ alone module: L<Test::Harness::Straps>.
85
+
86
+ See L<TAP::Parser>, L<TAP::Harness> for the main documentation for this
87
+ distribution.
88
+
89
+ =head1 FUNCTIONS
90
+
91
+ The following functions are available.
92
+
93
+ =head2 runtests( @test_files )
94
+
95
+ This runs all the given I<@test_files> and divines whether they passed
96
+ or failed based on their output to STDOUT (details above). It prints
97
+ out each individual test which failed along with a summary report and
98
+ a how long it all took.
99
+
100
+ It returns true if everything was ok. Otherwise it will C<die()> with
101
+ one of the messages in the DIAGNOSTICS section.
102
+
103
+ =cut
104
+
105
+ sub _has_taint {
106
+ my $test = shift;
107
+ return TAP::Parser::SourceHandler::Perl->get_taint(
108
+ TAP::Parser::Source->shebang($test) );
109
+ }
110
+
111
+ sub _aggregate {
112
+ my ( $harness, $aggregate, @tests ) = @_;
113
+
114
+ # Don't propagate to our children
115
+ local $ENV{HARNESS_OPTIONS};
116
+
117
+ _apply_extra_INC($harness);
118
+ _aggregate_tests( $harness, $aggregate, @tests );
119
+ }
120
+
121
+ # Make sure the child sees all the extra junk in @INC
122
+ sub _apply_extra_INC {
123
+ my $harness = shift;
124
+
125
+ $harness->callback(
126
+ parser_args => sub {
127
+ my ( $args, $test ) = @_;
128
+ push @{ $args->{switches} }, map {"-I$_"} _filtered_inc();
129
+ }
130
+ );
131
+ }
132
+
133
+ sub _aggregate_tests {
134
+ my ( $harness, $aggregate, @tests ) = @_;
135
+ $aggregate->start();
136
+ $harness->aggregate_tests( $aggregate, @tests );
137
+ $aggregate->stop();
138
+
139
+ }
140
+
141
+ sub runtests {
142
+ my @tests = @_;
143
+
144
+ # shield against -l
145
+ local ( $\, $, );
146
+
147
+ my $harness = _new_harness();
148
+ local $ENV{PERL_USE_UNSAFE_INC} = 1 if not exists $ENV{PERL_USE_UNSAFE_INC};
149
+
150
+ # Don't propagate to our children
151
+ local $ENV{HARNESS_OPTIONS};
152
+ my $aggregate = $harness->runtests(@tests);
153
+
154
+ my $total = $aggregate->total;
155
+ my $passed = $aggregate->passed;
156
+ my $failed = $aggregate->failed;
157
+ my $total_files = $aggregate->total_files;
158
+ my $failed_files = $aggregate->failed_files;
159
+
160
+ die(sprintf(
161
+ "Failed %d/%d test programs. %d/%d subtests failed.\n",
162
+ $failed_files, $total_files, $failed, $total
163
+ )
164
+ ) if $failed_files;
165
+
166
+ return $total && $total == $passed;
167
+ }
168
+
169
+ sub _canon {
170
+ my @list = sort { $a <=> $b } @_;
171
+ my @ranges = ();
172
+ my $count = scalar @list;
173
+ my $pos = 0;
174
+
175
+ while ( $pos < $count ) {
176
+ my $end = $pos + 1;
177
+ $end++ while $end < $count && $list[$end] <= $list[ $end - 1 ] + 1;
178
+ push @ranges, ( $end == $pos + 1 )
179
+ ? $list[$pos]
180
+ : join( '-', $list[$pos], $list[ $end - 1 ] );
181
+ $pos = $end;
182
+ }
183
+
184
+ return join( ' ', @ranges );
185
+ }
186
+
187
+ sub _new_harness {
188
+ my $sub_args = shift || {};
189
+
190
+ my ( @lib, @switches );
191
+ my @opt = map { shellwords($_) } grep { defined } $Switches, $ENV{HARNESS_PERL_SWITCHES};
192
+ while ( my $opt = shift @opt ) {
193
+ if ( $opt =~ /^ -I (.*) $ /x ) {
194
+ push @lib, length($1) ? $1 : shift @opt;
195
+ }
196
+ else {
197
+ push @switches, $opt;
198
+ }
199
+ }
200
+
201
+ push @lib, _filtered_inc();
202
+
203
+ # If $Verbose isn't numeric default to 1. This helps core.
204
+ my $verbosity = ( $Verbose ? ( $Verbose !~ /\d/ ) ? 1 : $Verbose : 0 );
205
+
206
+ my $args = {
207
+ timer => $Timer,
208
+ directives => our $Directives,
209
+ lib => \@lib,
210
+ switches => \@switches,
211
+ color => $Color,
212
+ verbosity => $verbosity,
213
+ ignore_exit => $IgnoreExit,
214
+ };
215
+
216
+ $args->{stdout} = $sub_args->{out}
217
+ if exists $sub_args->{out};
218
+
219
+ my $class = $ENV{HARNESS_SUBCLASS} || 'TAP::Harness';
220
+ if ( defined( my $env_opt = $ENV{HARNESS_OPTIONS} ) ) {
221
+ for my $opt ( split /:/, $env_opt ) {
222
+ if ( $opt =~ /^j(\d*)$/ ) {
223
+ $args->{jobs} = $1 || 9;
224
+ }
225
+ elsif ( $opt eq 'c' ) {
226
+ $args->{color} = 1;
227
+ }
228
+ elsif ( $opt =~ m/^f(.*)$/ ) {
229
+ my $fmt = $1;
230
+ $fmt =~ s/-/::/g;
231
+ $args->{formatter_class} = $fmt;
232
+ }
233
+ elsif ( $opt =~ m/^a(.*)$/ ) {
234
+ my $archive = $1;
235
+ $class = "TAP::Harness::Archive";
236
+ $args->{archive} = $archive;
237
+ }
238
+ else {
239
+ die "Unknown HARNESS_OPTIONS item: $opt\n";
240
+ }
241
+ }
242
+ }
243
+
244
+ return TAP::Harness->_construct( $class, $args );
245
+ }
246
+
247
+ # Get the parts of @INC which are changed from the stock list AND
248
+ # preserve reordering of stock directories.
249
+ sub _filtered_inc {
250
+ my @inc = grep { !ref } @INC; #28567
251
+
252
+ if (IS_VMS) {
253
+
254
+ # VMS has a 255-byte limit on the length of %ENV entries, so
255
+ # toss the ones that involve perl_root, the install location
256
+ @inc = grep !/perl_root/i, @inc;
257
+
258
+ }
259
+ elsif (IS_WIN32) {
260
+
261
+ # Lose any trailing backslashes in the Win32 paths
262
+ s/[\\\/]+$// for @inc;
263
+ }
264
+
265
+ my @default_inc = _default_inc();
266
+
267
+ my @new_inc;
268
+ my %seen;
269
+ for my $dir (@inc) {
270
+ next if $seen{$dir}++;
271
+
272
+ if ( $dir eq ( $default_inc[0] || '' ) ) {
273
+ shift @default_inc;
274
+ }
275
+ else {
276
+ push @new_inc, $dir;
277
+ }
278
+
279
+ shift @default_inc while @default_inc and $seen{ $default_inc[0] };
280
+ }
281
+
282
+ return @new_inc;
283
+ }
284
+
285
+ {
286
+
287
+ # Cache this to avoid repeatedly shelling out to Perl.
288
+ my @inc;
289
+
290
+ sub _default_inc {
291
+ return @inc if @inc;
292
+
293
+ local $ENV{PERL5LIB};
294
+ local $ENV{PERLLIB};
295
+
296
+ my $perl = $ENV{HARNESS_PERL} || $^X;
297
+
298
+ # Avoid using -l for the benefit of Perl 6
299
+ chomp( @inc = `"$perl" -e "print join qq[\\n], \@INC, q[]"` );
300
+ return @inc;
301
+ }
302
+ }
303
+
304
+ sub _check_sequence {
305
+ my @list = @_;
306
+ my $prev;
307
+ while ( my $next = shift @list ) {
308
+ return if defined $prev && $next <= $prev;
309
+ $prev = $next;
310
+ }
311
+
312
+ return 1;
313
+ }
314
+
315
+ sub execute_tests {
316
+ my %args = @_;
317
+
318
+ my $harness = _new_harness( \%args );
319
+ my $aggregate = TAP::Parser::Aggregator->new();
320
+
321
+ my %tot = (
322
+ bonus => 0,
323
+ max => 0,
324
+ ok => 0,
325
+ bad => 0,
326
+ good => 0,
327
+ files => 0,
328
+ tests => 0,
329
+ sub_skipped => 0,
330
+ todo => 0,
331
+ skipped => 0,
332
+ bench => undef,
333
+ );
334
+
335
+ # Install a callback so we get to see any plans the
336
+ # harness executes.
337
+ $harness->callback(
338
+ made_parser => sub {
339
+ my $parser = shift;
340
+ $parser->callback(
341
+ plan => sub {
342
+ my $plan = shift;
343
+ if ( $plan->directive eq 'SKIP' ) {
344
+ $tot{skipped}++;
345
+ }
346
+ }
347
+ );
348
+ }
349
+ );
350
+
351
+ local $ENV{PERL_USE_UNSAFE_INC} = 1 if not exists $ENV{PERL_USE_UNSAFE_INC};
352
+ _aggregate( $harness, $aggregate, @{ $args{tests} } );
353
+
354
+ $tot{bench} = $aggregate->elapsed;
355
+ my @tests = $aggregate->descriptions;
356
+
357
+ # TODO: Work out the circumstances under which the files
358
+ # and tests totals can differ.
359
+ $tot{files} = $tot{tests} = scalar @tests;
360
+
361
+ my %failedtests = ();
362
+ my %todo_passed = ();
363
+
364
+ for my $test (@tests) {
365
+ my ($parser) = $aggregate->parsers($test);
366
+
367
+ my @failed = $parser->failed;
368
+
369
+ my $wstat = $parser->wait;
370
+ my $estat = $parser->exit;
371
+ my $planned = $parser->tests_planned;
372
+ my @errors = $parser->parse_errors;
373
+ my $passed = $parser->passed;
374
+ my $actual_passed = $parser->actual_passed;
375
+
376
+ my $ok_seq = _check_sequence( $parser->actual_passed );
377
+
378
+ # Duplicate exit, wait status semantics of old version
379
+ $estat ||= '' unless $wstat;
380
+ $wstat ||= '';
381
+
382
+ $tot{max} += ( $planned || 0 );
383
+ $tot{bonus} += $parser->todo_passed;
384
+ $tot{ok} += $passed > $actual_passed ? $passed : $actual_passed;
385
+ $tot{sub_skipped} += $parser->skipped;
386
+ $tot{todo} += $parser->todo;
387
+
388
+ if ( @failed || $estat || @errors ) {
389
+ $tot{bad}++;
390
+
391
+ my $huh_planned = $planned ? undef : '??';
392
+ my $huh_errors = $ok_seq ? undef : '??';
393
+
394
+ $failedtests{$test} = {
395
+ 'canon' => $huh_planned
396
+ || $huh_errors
397
+ || _canon(@failed)
398
+ || '??',
399
+ 'estat' => $estat,
400
+ 'failed' => $huh_planned
401
+ || $huh_errors
402
+ || scalar @failed,
403
+ 'max' => $huh_planned || $planned,
404
+ 'name' => $test,
405
+ 'wstat' => $wstat
406
+ };
407
+ }
408
+ else {
409
+ $tot{good}++;
410
+ }
411
+
412
+ my @todo = $parser->todo_passed;
413
+ if (@todo) {
414
+ $todo_passed{$test} = {
415
+ 'canon' => _canon(@todo),
416
+ 'estat' => $estat,
417
+ 'failed' => scalar @todo,
418
+ 'max' => scalar $parser->todo,
419
+ 'name' => $test,
420
+ 'wstat' => $wstat
421
+ };
422
+ }
423
+ }
424
+
425
+ return ( \%tot, \%failedtests, \%todo_passed );
426
+ }
427
+
428
+ =head2 execute_tests( tests => \@test_files, out => \*FH )
429
+
430
+ Runs all the given C<@test_files> (just like C<runtests()>) but
431
+ doesn't generate the final report. During testing, progress
432
+ information will be written to the currently selected output
433
+ filehandle (usually C<STDOUT>), or to the filehandle given by the
434
+ C<out> parameter. The I<out> is optional.
435
+
436
+ Returns a list of two values, C<$total> and C<$failed>, describing the
437
+ results. C<$total> is a hash ref summary of all the tests run. Its
438
+ keys and values are this:
439
+
440
+ bonus Number of individual todo tests unexpectedly passed
441
+ max Number of individual tests ran
442
+ ok Number of individual tests passed
443
+ sub_skipped Number of individual tests skipped
444
+ todo Number of individual todo tests
445
+
446
+ files Number of test files ran
447
+ good Number of test files passed
448
+ bad Number of test files failed
449
+ tests Number of test files originally given
450
+ skipped Number of test files skipped
451
+
452
+ If C<< $total->{bad} == 0 >> and C<< $total->{max} > 0 >>, you've
453
+ got a successful test.
454
+
455
+ C<$failed> is a hash ref of all the test scripts that failed. Each key
456
+ is the name of a test script, each value is another hash representing
457
+ how that script failed. Its keys are these:
458
+
459
+ name Name of the test which failed
460
+ estat Script's exit value
461
+ wstat Script's wait status
462
+ max Number of individual tests
463
+ failed Number which failed
464
+ canon List of tests which failed (as string).
465
+
466
+ C<$failed> should be empty if everything passed.
467
+
468
+ =cut
469
+
470
+ 1;
471
+ __END__
472
+
473
+ =head1 EXPORT
474
+
475
+ C<&runtests> is exported by C<Test::Harness> by default.
476
+
477
+ C<&execute_tests>, C<$verbose>, C<$switches> and C<$debug> are
478
+ exported upon request.
479
+
480
+ =head1 ENVIRONMENT VARIABLES THAT TAP::HARNESS::COMPATIBLE SETS
481
+
482
+ C<Test::Harness> sets these before executing the individual tests.
483
+
484
+ =over 4
485
+
486
+ =item C<HARNESS_ACTIVE>
487
+
488
+ This is set to a true value. It allows the tests to determine if they
489
+ are being executed through the harness or by any other means.
490
+
491
+ =item C<HARNESS_VERSION>
492
+
493
+ This is the version of C<Test::Harness>.
494
+
495
+ =back
496
+
497
+ =head1 ENVIRONMENT VARIABLES THAT AFFECT TEST::HARNESS
498
+
499
+ =over 4
500
+
501
+ =item C<HARNESS_PERL_SWITCHES>
502
+
503
+ Setting this adds perl command line switches to each test file run.
504
+
505
+ For example, C<HARNESS_PERL_SWITCHES=-T> will turn on taint mode.
506
+ C<HARNESS_PERL_SWITCHES=-MDevel::Cover> will run C<Devel::Cover> for
507
+ each test.
508
+
509
+ C<-w> is always set. You can turn this off in the test with C<BEGIN {
510
+ $^W = 0 }>.
511
+
512
+ =item C<HARNESS_TIMER>
513
+
514
+ Setting this to true will make the harness display the number of
515
+ milliseconds each test took. You can also use F<prove>'s C<--timer>
516
+ switch.
517
+
518
+ =item C<HARNESS_VERBOSE>
519
+
520
+ If true, C<Test::Harness> will output the verbose results of running
521
+ its tests. Setting C<$Test::Harness::verbose> will override this,
522
+ or you can use the C<-v> switch in the F<prove> utility.
523
+
524
+ =item C<HARNESS_OPTIONS>
525
+
526
+ Provide additional options to the harness. Currently supported options are:
527
+
528
+ =over
529
+
530
+ =item C<< j<n> >>
531
+
532
+ Run <n> (default 9) parallel jobs.
533
+
534
+ =item C<< c >>
535
+
536
+ Try to color output. See L<TAP::Formatter::Base/"new">.
537
+
538
+ =item C<< a<file.tgz> >>
539
+
540
+ Will use L<TAP::Harness::Archive> as the harness class, and save the TAP to
541
+ C<file.tgz>
542
+
543
+ =item C<< fPackage-With-Dashes >>
544
+
545
+ Set the formatter_class of the harness being run. Since the C<HARNESS_OPTIONS>
546
+ is separated by C<:>, we use C<-> instead.
547
+
548
+ =back
549
+
550
+ Multiple options may be separated by colons:
551
+
552
+ HARNESS_OPTIONS=j9:c make test
553
+
554
+ =item C<HARNESS_SUBCLASS>
555
+
556
+ Specifies a TAP::Harness subclass to be used in place of TAP::Harness.
557
+
558
+ =item C<HARNESS_SUMMARY_COLOR_SUCCESS>
559
+
560
+ Determines the L<Term::ANSIColor> for the summary in case it is successful.
561
+ This color defaults to C<'green'>.
562
+
563
+ =item C<HARNESS_SUMMARY_COLOR_FAIL>
564
+
565
+ Determines the L<Term::ANSIColor> for the failure in case it is successful.
566
+ This color defaults to C<'red'>.
567
+
568
+ =back
569
+
570
+ =head1 Taint Mode
571
+
572
+ Normally when a Perl program is run in taint mode the contents of the
573
+ C<PERL5LIB> environment variable do not appear in C<@INC>.
574
+
575
+ Because C<PERL5LIB> is often used during testing to add build
576
+ directories to C<@INC> C<Test::Harness> passes the names of any
577
+ directories found in C<PERL5LIB> as -I switches. The net effect of this
578
+ is that C<PERL5LIB> is honoured even in taint mode.
579
+
580
+ =head1 SEE ALSO
581
+
582
+ L<TAP::Harness>
583
+
584
+ =head1 BUGS
585
+
586
+ Please report any bugs or feature requests to
587
+ C<bug-test-harness at rt.cpan.org>, or through the web interface at
588
+ L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Harness>. I will be
589
+ notified, and then you'll automatically be notified of progress on your bug
590
+ as I make changes.
591
+
592
+ =head1 AUTHORS
593
+
594
+ Andy Armstrong C<< <andy@hexten.net> >>
595
+
596
+ L<Test::Harness> 2.64 (maintained by Andy Lester and on which this
597
+ module is based) has this attribution:
598
+
599
+ Either Tim Bunce or Andreas Koenig, we don't know. What we know for
600
+ sure is, that it was inspired by Larry Wall's F<TEST> script that came
601
+ with perl distributions for ages. Numerous anonymous contributors
602
+ exist. Andreas Koenig held the torch for many years, and then
603
+ Michael G Schwern.
604
+
605
+ =head1 LICENCE AND COPYRIGHT
606
+
607
+ Copyright (c) 2007-2011, Andy Armstrong C<< <andy@hexten.net> >>. All rights reserved.
608
+
609
+ This module is free software; you can redistribute it and/or
610
+ modify it under the same terms as Perl itself. See L<perlartistic>.
611
+
git/usr/share/perl5/core_perl/Test/More.pm ADDED
@@ -0,0 +1,2047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test::More;
2
+
3
+ use 5.006;
4
+ use strict;
5
+ use warnings;
6
+
7
+ #---- perlcritic exemptions. ----#
8
+
9
+ # We use a lot of subroutine prototypes
10
+ ## no critic (Subroutines::ProhibitSubroutinePrototypes)
11
+
12
+ # Can't use Carp because it might cause C<use_ok()> to accidentally succeed
13
+ # even though the module being used forgot to use Carp. Yes, this
14
+ # actually happened.
15
+ sub _carp {
16
+ my( $file, $line ) = ( caller(1) )[ 1, 2 ];
17
+ return warn @_, " at $file line $line\n";
18
+ }
19
+
20
+ our $VERSION = '1.302210';
21
+
22
+ use Test::Builder::Module;
23
+ our @ISA = qw(Test::Builder::Module);
24
+ our @EXPORT = qw(ok use_ok require_ok
25
+ is isnt like unlike is_deeply
26
+ cmp_ok
27
+ skip todo todo_skip
28
+ pass fail
29
+ eq_array eq_hash eq_set
30
+ $TODO
31
+ plan
32
+ done_testing
33
+ can_ok isa_ok new_ok
34
+ diag note explain
35
+ subtest
36
+ BAIL_OUT
37
+ );
38
+
39
+ =head1 NAME
40
+
41
+ Test::More - yet another framework for writing test scripts
42
+
43
+ =head1 SYNOPSIS
44
+
45
+ use Test::More tests => 23;
46
+ # or
47
+ use Test::More skip_all => $reason;
48
+ # or
49
+ use Test::More; # see done_testing()
50
+
51
+ require_ok( 'Some::Module' );
52
+
53
+ # Various ways to say "ok"
54
+ ok($got eq $expected, $test_name);
55
+
56
+ is ($got, $expected, $test_name);
57
+ isnt($got, $expected, $test_name);
58
+
59
+ # Rather than print STDERR "# here's what went wrong\n"
60
+ diag("here's what went wrong");
61
+
62
+ like ($got, qr/expected/, $test_name);
63
+ unlike($got, qr/expected/, $test_name);
64
+
65
+ cmp_ok($got, '==', $expected, $test_name);
66
+
67
+ is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
68
+
69
+ SKIP: {
70
+ skip $why, $how_many unless $have_some_feature;
71
+
72
+ ok( foo(), $test_name );
73
+ is( foo(42), 23, $test_name );
74
+ };
75
+
76
+ TODO: {
77
+ local $TODO = $why;
78
+
79
+ ok( foo(), $test_name );
80
+ is( foo(42), 23, $test_name );
81
+ };
82
+
83
+ can_ok($module, @methods);
84
+ isa_ok($object, $class);
85
+
86
+ pass($test_name);
87
+ fail($test_name);
88
+
89
+ BAIL_OUT($why);
90
+
91
+ # UNIMPLEMENTED!!!
92
+ my @status = Test::More::status;
93
+
94
+
95
+ =head1 DESCRIPTION
96
+
97
+ B<STOP!> If you're just getting started writing tests, have a look at
98
+ L<Test2::Suite> first.
99
+
100
+ This is a drop in replacement for Test::Simple which you can switch to once you
101
+ get the hang of basic testing.
102
+
103
+ The purpose of this module is to provide a wide range of testing
104
+ utilities. Various ways to say "ok" with better diagnostics,
105
+ facilities to skip tests, test future features and compare complicated
106
+ data structures. While you can do almost anything with a simple
107
+ C<ok()> function, it doesn't provide good diagnostic output.
108
+
109
+
110
+ =head2 I love it when a plan comes together
111
+
112
+ Before anything else, you need a testing plan. This basically declares
113
+ how many tests your script is going to run to protect against premature
114
+ failure.
115
+
116
+ The preferred way to do this is to declare a plan when you C<use Test::More>.
117
+
118
+ use Test::More tests => 23;
119
+
120
+ There are cases when you will not know beforehand how many tests your
121
+ script is going to run. In this case, you can declare your tests at
122
+ the end.
123
+
124
+ use Test::More;
125
+
126
+ ... run your tests ...
127
+
128
+ done_testing( $number_of_tests_run );
129
+
130
+ B<NOTE> C<done_testing()> should never be called in an C<END { ... }> block.
131
+
132
+ Sometimes you really don't know how many tests were run, or it's too
133
+ difficult to calculate. In which case you can leave off
134
+ $number_of_tests_run.
135
+
136
+ In some cases, you'll want to completely skip an entire testing script.
137
+
138
+ use Test::More skip_all => $skip_reason;
139
+
140
+ Your script will declare a skip with the reason why you skipped and
141
+ exit immediately with a zero (success). See L<Test::Harness> for
142
+ details.
143
+
144
+ If you want to control what functions Test::More will export, you
145
+ have to use the 'import' option. For example, to import everything
146
+ but 'fail', you'd do:
147
+
148
+ use Test::More tests => 23, import => ['!fail'];
149
+
150
+ Alternatively, you can use the C<plan()> function. Useful for when you
151
+ have to calculate the number of tests.
152
+
153
+ use Test::More;
154
+ plan tests => keys %Stuff * 3;
155
+
156
+ or for deciding between running the tests at all:
157
+
158
+ use Test::More;
159
+ if( $^O eq 'MacOS' ) {
160
+ plan skip_all => 'Test irrelevant on MacOS';
161
+ }
162
+ else {
163
+ plan tests => 42;
164
+ }
165
+
166
+ =cut
167
+
168
+ sub plan {
169
+ my $tb = Test::More->builder;
170
+
171
+ return $tb->plan(@_);
172
+ }
173
+
174
+ # This implements "use Test::More 'no_diag'" but the behavior is
175
+ # deprecated.
176
+ sub import_extra {
177
+ my $class = shift;
178
+ my $list = shift;
179
+
180
+ my @other;
181
+ my $idx = 0;
182
+ my $import;
183
+ while( $idx <= $#{$list} ) {
184
+ my $item = $list->[$idx];
185
+
186
+ if( defined $item and $item eq 'no_diag' ) {
187
+ $class->builder->no_diag(1);
188
+ }
189
+ elsif( defined $item and $item eq 'import' ) {
190
+ if ($import) {
191
+ push @$import, @{$list->[ ++$idx ]};
192
+ }
193
+ else {
194
+ $import = $list->[ ++$idx ];
195
+ push @other, $item, $import;
196
+ }
197
+ }
198
+ else {
199
+ push @other, $item;
200
+ }
201
+
202
+ $idx++;
203
+ }
204
+
205
+ @$list = @other;
206
+
207
+ if ($class eq __PACKAGE__ && (!$import || grep $_ eq '$TODO', @$import)) {
208
+ my $to = $class->builder->exported_to;
209
+ no strict 'refs';
210
+ *{"$to\::TODO"} = \our $TODO;
211
+ if ($import) {
212
+ @$import = grep $_ ne '$TODO', @$import;
213
+ }
214
+ else {
215
+ push @$list, import => [grep $_ ne '$TODO', @EXPORT];
216
+ }
217
+ }
218
+
219
+ return;
220
+ }
221
+
222
+ =over 4
223
+
224
+ =item B<done_testing>
225
+
226
+ done_testing();
227
+ done_testing($number_of_tests);
228
+
229
+ If you don't know how many tests you're going to run, you can issue
230
+ the plan when you're done running tests.
231
+
232
+ $number_of_tests is the same as C<plan()>, it's the number of tests you
233
+ expected to run. You can omit this, in which case the number of tests
234
+ you ran doesn't matter, just the fact that your tests ran to
235
+ conclusion.
236
+
237
+ This is safer than and replaces the "no_plan" plan.
238
+
239
+ B<Note:> You must never put C<done_testing()> inside an C<END { ... }> block.
240
+ The plan is there to ensure your test does not exit before testing has
241
+ completed. If you use an END block you completely bypass this protection.
242
+
243
+ =back
244
+
245
+ =cut
246
+
247
+ sub done_testing {
248
+ my $tb = Test::More->builder;
249
+ $tb->done_testing(@_);
250
+ }
251
+
252
+ =head2 Test names
253
+
254
+ By convention, each test is assigned a number in order. This is
255
+ largely done automatically for you. However, it's often very useful to
256
+ assign a name to each test. Which would you rather see:
257
+
258
+ ok 4
259
+ not ok 5
260
+ ok 6
261
+
262
+ or
263
+
264
+ ok 4 - basic multi-variable
265
+ not ok 5 - simple exponential
266
+ ok 6 - force == mass * acceleration
267
+
268
+ The later gives you some idea of what failed. It also makes it easier
269
+ to find the test in your script, simply search for "simple
270
+ exponential".
271
+
272
+ All test functions take a name argument. It's optional, but highly
273
+ suggested that you use it.
274
+
275
+ =head2 I'm ok, you're not ok.
276
+
277
+ The basic purpose of this module is to print out either "ok #" or "not
278
+ ok #" depending on if a given test succeeded or failed. Everything
279
+ else is just gravy.
280
+
281
+ All of the following print "ok" or "not ok" depending on if the test
282
+ succeeded or failed. They all also return true or false,
283
+ respectively.
284
+
285
+ =over 4
286
+
287
+ =item B<ok>
288
+
289
+ ok($got eq $expected, $test_name);
290
+
291
+ This simply evaluates any expression (C<$got eq $expected> is just a
292
+ simple example) and uses that to determine if the test succeeded or
293
+ failed. A true expression passes, a false one fails. Very simple.
294
+
295
+ For example:
296
+
297
+ ok( $exp{9} == 81, 'simple exponential' );
298
+ ok( Film->can('db_Main'), 'set_db()' );
299
+ ok( $p->tests == 4, 'saw tests' );
300
+ ok( !grep(!defined $_, @items), 'all items defined' );
301
+
302
+ (Mnemonic: "This is ok.")
303
+
304
+ $test_name is a very short description of the test that will be printed
305
+ out. It makes it very easy to find a test in your script when it fails
306
+ and gives others an idea of your intentions. $test_name is optional,
307
+ but we B<very> strongly encourage its use.
308
+
309
+ Should an C<ok()> fail, it will produce some diagnostics:
310
+
311
+ not ok 18 - sufficient mucus
312
+ # Failed test 'sufficient mucus'
313
+ # in foo.t at line 42.
314
+
315
+ This is the same as L<Test::Simple>'s C<ok()> routine.
316
+
317
+ =cut
318
+
319
+ sub ok ($;$) {
320
+ my( $test, $name ) = @_;
321
+ my $tb = Test::More->builder;
322
+
323
+ return $tb->ok( $test, $name );
324
+ }
325
+
326
+ =item B<is>
327
+
328
+ =item B<isnt>
329
+
330
+ is ( $got, $expected, $test_name );
331
+ isnt( $got, $expected, $test_name );
332
+
333
+ Similar to C<ok()>, C<is()> and C<isnt()> compare their two arguments
334
+ with C<eq> and C<ne> respectively and use the result of that to
335
+ determine if the test succeeded or failed. So these:
336
+
337
+ # Is the ultimate answer 42?
338
+ is( ultimate_answer(), 42, "Meaning of Life" );
339
+
340
+ # $foo isn't empty
341
+ isnt( $foo, '', "Got some foo" );
342
+
343
+ are similar to these:
344
+
345
+ ok( ultimate_answer() eq 42, "Meaning of Life" );
346
+ ok( $foo ne '', "Got some foo" );
347
+
348
+ C<undef> will only ever match C<undef>. So you can test a value
349
+ against C<undef> like this:
350
+
351
+ is($not_defined, undef, "undefined as expected");
352
+
353
+ (Mnemonic: "This is that." "This isn't that.")
354
+
355
+ So why use these? They produce better diagnostics on failure. C<ok()>
356
+ cannot know what you are testing for (beyond the name), but C<is()> and
357
+ C<isnt()> know what the test was and why it failed. For example this
358
+ test:
359
+
360
+ my $foo = 'waffle'; my $bar = 'yarblokos';
361
+ is( $foo, $bar, 'Is foo the same as bar?' );
362
+
363
+ Will produce something like this:
364
+
365
+ not ok 17 - Is foo the same as bar?
366
+ # Failed test 'Is foo the same as bar?'
367
+ # in foo.t at line 139.
368
+ # got: 'waffle'
369
+ # expected: 'yarblokos'
370
+
371
+ So you can figure out what went wrong without rerunning the test.
372
+
373
+ You are encouraged to use C<is()> and C<isnt()> over C<ok()> where possible,
374
+ however do not be tempted to use them to find out if something is
375
+ true or false!
376
+
377
+ # XXX BAD!
378
+ is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
379
+
380
+ This does not check if C<exists $brooklyn{tree}> is true, it checks if
381
+ it returns 1. Very different. Similar caveats exist for false and 0.
382
+ In these cases, use C<ok()>.
383
+
384
+ ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
385
+
386
+ A simple call to C<isnt()> usually does not provide a strong test but there
387
+ are cases when you cannot say much more about a value than that it is
388
+ different from some other value:
389
+
390
+ new_ok $obj, "Foo";
391
+
392
+ my $clone = $obj->clone;
393
+ isa_ok $obj, "Foo", "Foo->clone";
394
+
395
+ isnt $obj, $clone, "clone() produces a different object";
396
+
397
+ Historically we supported an C<isn't()> function as an alias of
398
+ C<isnt()>, however in Perl 5.37.9 support for the use of apostrophe as
399
+ a package separator was deprecated and by Perl 5.42.0 support for it
400
+ will have been removed completely. Accordingly use of C<isn't()> is also
401
+ deprecated, and will produce warnings when used unless 'deprecated'
402
+ warnings are specifically disabled in the scope where it is used. You
403
+ are strongly advised to migrate to using C<isnt()> instead.
404
+
405
+ =cut
406
+
407
+ sub is ($$;$) {
408
+ my $tb = Test::More->builder;
409
+
410
+ return $tb->is_eq(@_);
411
+ }
412
+
413
+ sub isnt ($$;$) {
414
+ my $tb = Test::More->builder;
415
+
416
+ return $tb->isnt_eq(@_);
417
+ }
418
+
419
+ # Historically it was possible to use apostrophes as a package
420
+ # separator. make this available as isn't() for perl's that support it.
421
+ # However in 5.37.9 the apostrophe as a package separator was
422
+ # deprecated, so warn users of isn't() that they should use isnt()
423
+ # instead. We assume that if they are calling isn::t() they are doing so
424
+ # via isn't() as we have no way to be sure that they aren't spelling it
425
+ # with a double colon. We only trigger the warning if deprecation
426
+ # warnings are enabled, so the user can silence the warning if they
427
+ # wish.
428
+ sub isn::t {
429
+ local ($@, $!, $?);
430
+ if (warnings::enabled("deprecated")) {
431
+ _carp
432
+ "Use of apostrophe as package separator was deprecated in Perl 5.37.9,\n",
433
+ "and will be removed in Perl 5.42.0. You should change code that uses\n",
434
+ "Test::More::isn't() to use Test::More::isnt() as a replacement";
435
+ }
436
+ goto &isnt;
437
+ }
438
+
439
+ =item B<like>
440
+
441
+ like( $got, qr/expected/, $test_name );
442
+
443
+ Similar to C<ok()>, C<like()> matches $got against the regex C<qr/expected/>.
444
+
445
+ So this:
446
+
447
+ like($got, qr/expected/, 'this is like that');
448
+
449
+ is similar to:
450
+
451
+ ok( $got =~ m/expected/, 'this is like that');
452
+
453
+ (Mnemonic "This is like that".)
454
+
455
+ The second argument is a regular expression. It may be given as a
456
+ regex reference (i.e. C<qr//>) or (for better compatibility with older
457
+ perls) as a string that looks like a regex (alternative delimiters are
458
+ currently not supported):
459
+
460
+ like( $got, '/expected/', 'this is like that' );
461
+
462
+ Regex options may be placed on the end (C<'/expected/i'>).
463
+
464
+ Its advantages over C<ok()> are similar to that of C<is()> and C<isnt()>. Better
465
+ diagnostics on failure.
466
+
467
+ =cut
468
+
469
+ sub like ($$;$) {
470
+ my $tb = Test::More->builder;
471
+
472
+ return $tb->like(@_);
473
+ }
474
+
475
+ =item B<unlike>
476
+
477
+ unlike( $got, qr/expected/, $test_name );
478
+
479
+ Works exactly as C<like()>, only it checks if $got B<does not> match the
480
+ given pattern.
481
+
482
+ =cut
483
+
484
+ sub unlike ($$;$) {
485
+ my $tb = Test::More->builder;
486
+
487
+ return $tb->unlike(@_);
488
+ }
489
+
490
+ =item B<cmp_ok>
491
+
492
+ cmp_ok( $got, $op, $expected, $test_name );
493
+
494
+ Halfway between C<ok()> and C<is()> lies C<cmp_ok()>. This allows you
495
+ to compare two arguments using any binary perl operator. The test
496
+ passes if the comparison is true and fails otherwise.
497
+
498
+ # ok( $got eq $expected );
499
+ cmp_ok( $got, 'eq', $expected, 'this eq that' );
500
+
501
+ # ok( $got == $expected );
502
+ cmp_ok( $got, '==', $expected, 'this == that' );
503
+
504
+ # ok( $got && $expected );
505
+ cmp_ok( $got, '&&', $expected, 'this && that' );
506
+ ...etc...
507
+
508
+ Its advantage over C<ok()> is when the test fails you'll know what $got
509
+ and $expected were:
510
+
511
+ not ok 1
512
+ # Failed test in foo.t at line 12.
513
+ # '23'
514
+ # &&
515
+ # undef
516
+
517
+ It's also useful in those cases where you are comparing numbers and
518
+ C<is()>'s use of C<eq> will interfere:
519
+
520
+ cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
521
+
522
+ It's especially useful when comparing greater-than or smaller-than
523
+ relation between values:
524
+
525
+ cmp_ok( $some_value, '<=', $upper_limit );
526
+
527
+
528
+ =cut
529
+
530
+ sub cmp_ok($$$;$) {
531
+ my $tb = Test::More->builder;
532
+
533
+ return $tb->cmp_ok(@_);
534
+ }
535
+
536
+ =item B<can_ok>
537
+
538
+ can_ok($module, @methods);
539
+ can_ok($object, @methods);
540
+
541
+ Checks to make sure the $module or $object can do these @methods
542
+ (works with functions, too).
543
+
544
+ can_ok('Foo', qw(this that whatever));
545
+
546
+ is almost exactly like saying:
547
+
548
+ ok( Foo->can('this') &&
549
+ Foo->can('that') &&
550
+ Foo->can('whatever')
551
+ );
552
+
553
+ only without all the typing and with a better interface. Handy for
554
+ quickly testing an interface.
555
+
556
+ No matter how many @methods you check, a single C<can_ok()> call counts
557
+ as one test. If you desire otherwise, use:
558
+
559
+ foreach my $meth (@methods) {
560
+ can_ok('Foo', $meth);
561
+ }
562
+
563
+ =cut
564
+
565
+ sub can_ok ($@) {
566
+ my( $proto, @methods ) = @_;
567
+ my $class = ref $proto || $proto;
568
+ my $tb = Test::More->builder;
569
+
570
+ unless($class) {
571
+ my $ok = $tb->ok( 0, "->can(...)" );
572
+ $tb->diag(' can_ok() called with empty class or reference');
573
+ return $ok;
574
+ }
575
+
576
+ unless(@methods) {
577
+ my $ok = $tb->ok( 0, "$class->can(...)" );
578
+ $tb->diag(' can_ok() called with no methods');
579
+ return $ok;
580
+ }
581
+
582
+ my @nok;
583
+ foreach my $method (@methods) {
584
+ $tb->_try( sub { $proto->can($method) } ) or push @nok, $method;
585
+ }
586
+
587
+ my $name = (@methods == 1) ? "$class->can('$methods[0]')" :
588
+ "$class->can(...)" ;
589
+
590
+ my $ok = $tb->ok( !@nok, $name );
591
+
592
+ $tb->diag( map " $class->can('$_') failed\n", @nok );
593
+
594
+ return $ok;
595
+ }
596
+
597
+ =item B<isa_ok>
598
+
599
+ isa_ok($object, $class, $object_name);
600
+ isa_ok($subclass, $class, $object_name);
601
+ isa_ok($ref, $type, $ref_name);
602
+
603
+ Checks to see if the given C<< $object->isa($class) >>. Also checks to make
604
+ sure the object was defined in the first place. Handy for this sort
605
+ of thing:
606
+
607
+ my $obj = Some::Module->new;
608
+ isa_ok( $obj, 'Some::Module' );
609
+
610
+ where you'd otherwise have to write
611
+
612
+ my $obj = Some::Module->new;
613
+ ok( defined $obj && $obj->isa('Some::Module') );
614
+
615
+ to safeguard against your test script blowing up.
616
+
617
+ You can also test a class, to make sure that it has the right ancestor:
618
+
619
+ isa_ok( 'Vole', 'Rodent' );
620
+
621
+ It works on references, too:
622
+
623
+ isa_ok( $array_ref, 'ARRAY' );
624
+
625
+ The diagnostics of this test normally just refer to 'the object'. If
626
+ you'd like them to be more specific, you can supply an $object_name
627
+ (for example 'Test customer').
628
+
629
+ =cut
630
+
631
+ sub isa_ok ($$;$) {
632
+ my( $thing, $class, $thing_name ) = @_;
633
+ my $tb = Test::More->builder;
634
+
635
+ my $whatami;
636
+ if( !defined $thing ) {
637
+ $whatami = 'undef';
638
+ }
639
+ elsif( ref $thing ) {
640
+ $whatami = 'reference';
641
+
642
+ local($@,$!);
643
+ require Scalar::Util;
644
+ if( Scalar::Util::blessed($thing) ) {
645
+ $whatami = 'object';
646
+ }
647
+ }
648
+ else {
649
+ $whatami = 'class';
650
+ }
651
+
652
+ # We can't use UNIVERSAL::isa because we want to honor isa() overrides
653
+ my( $rslt, $error ) = $tb->_try( sub { $thing->isa($class) } );
654
+
655
+ if($error) {
656
+ die <<WHOA unless $error =~ /^Can't (locate|call) method "isa"/;
657
+ WHOA! I tried to call ->isa on your $whatami and got some weird error.
658
+ Here's the error.
659
+ $error
660
+ WHOA
661
+ }
662
+
663
+ # Special case for isa_ok( [], "ARRAY" ) and like
664
+ if( $whatami eq 'reference' ) {
665
+ $rslt = UNIVERSAL::isa($thing, $class);
666
+ }
667
+
668
+ my($diag, $name);
669
+ if( defined $thing_name ) {
670
+ $name = "'$thing_name' isa '$class'";
671
+ $diag = defined $thing ? "'$thing_name' isn't a '$class'" : "'$thing_name' isn't defined";
672
+ }
673
+ elsif( $whatami eq 'object' ) {
674
+ my $my_class = ref $thing;
675
+ $thing_name = qq[An object of class '$my_class'];
676
+ $name = "$thing_name isa '$class'";
677
+ $diag = "The object of class '$my_class' isn't a '$class'";
678
+ }
679
+ elsif( $whatami eq 'reference' ) {
680
+ my $type = ref $thing;
681
+ $thing_name = qq[A reference of type '$type'];
682
+ $name = "$thing_name isa '$class'";
683
+ $diag = "The reference of type '$type' isn't a '$class'";
684
+ }
685
+ elsif( $whatami eq 'undef' ) {
686
+ $thing_name = 'undef';
687
+ $name = "$thing_name isa '$class'";
688
+ $diag = "$thing_name isn't defined";
689
+ }
690
+ elsif( $whatami eq 'class' ) {
691
+ $thing_name = qq[The class (or class-like) '$thing'];
692
+ $name = "$thing_name isa '$class'";
693
+ $diag = "$thing_name isn't a '$class'";
694
+ }
695
+ else {
696
+ die;
697
+ }
698
+
699
+ my $ok;
700
+ if($rslt) {
701
+ $ok = $tb->ok( 1, $name );
702
+ }
703
+ else {
704
+ $ok = $tb->ok( 0, $name );
705
+ $tb->diag(" $diag\n");
706
+ }
707
+
708
+ return $ok;
709
+ }
710
+
711
+ =item B<new_ok>
712
+
713
+ my $obj = new_ok( $class );
714
+ my $obj = new_ok( $class => \@args );
715
+ my $obj = new_ok( $class => \@args, $object_name );
716
+
717
+ A convenience function which combines creating an object and calling
718
+ C<isa_ok()> on that object.
719
+
720
+ It is basically equivalent to:
721
+
722
+ my $obj = $class->new(@args);
723
+ isa_ok $obj, $class, $object_name;
724
+
725
+ If @args is not given, an empty list will be used.
726
+
727
+ This function only works on C<new()> and it assumes C<new()> will return
728
+ just a single object which isa C<$class>.
729
+
730
+ =cut
731
+
732
+ sub new_ok {
733
+ my $tb = Test::More->builder;
734
+ $tb->croak("new_ok() must be given at least a class") unless @_;
735
+
736
+ my( $class, $args, $object_name ) = @_;
737
+
738
+ $args ||= [];
739
+
740
+ my $obj;
741
+ my( $success, $error ) = $tb->_try( sub { $obj = $class->new(@$args); 1 } );
742
+ if($success) {
743
+ local $Test::Builder::Level = $Test::Builder::Level + 1;
744
+ isa_ok $obj, $class, $object_name;
745
+ }
746
+ else {
747
+ $class = 'undef' if !defined $class;
748
+ $tb->ok( 0, "$class->new() died" );
749
+ $tb->diag(" Error was: $error");
750
+ }
751
+
752
+ return $obj;
753
+ }
754
+
755
+ =item B<subtest>
756
+
757
+ subtest $name => \&code, @args;
758
+
759
+ C<subtest()> runs the &code as its own little test with its own plan and
760
+ its own result. The main test counts this as a single test using the
761
+ result of the whole subtest to determine if its ok or not ok.
762
+
763
+ For example...
764
+
765
+ use Test::More tests => 3;
766
+
767
+ pass("First test");
768
+
769
+ subtest 'An example subtest' => sub {
770
+ plan tests => 2;
771
+
772
+ pass("This is a subtest");
773
+ pass("So is this");
774
+ };
775
+
776
+ pass("Third test");
777
+
778
+ This would produce.
779
+
780
+ 1..3
781
+ ok 1 - First test
782
+ # Subtest: An example subtest
783
+ 1..2
784
+ ok 1 - This is a subtest
785
+ ok 2 - So is this
786
+ ok 2 - An example subtest
787
+ ok 3 - Third test
788
+
789
+ A subtest may call C<skip_all>. No tests will be run, but the subtest is
790
+ considered a skip.
791
+
792
+ subtest 'skippy' => sub {
793
+ plan skip_all => 'cuz I said so';
794
+ pass('this test will never be run');
795
+ };
796
+
797
+ Returns true if the subtest passed, false otherwise.
798
+
799
+ Due to how subtests work, you may omit a plan if you desire. This adds an
800
+ implicit C<done_testing()> to the end of your subtest. The following two
801
+ subtests are equivalent:
802
+
803
+ subtest 'subtest with implicit done_testing()', sub {
804
+ ok 1, 'subtests with an implicit done testing should work';
805
+ ok 1, '... and support more than one test';
806
+ ok 1, '... no matter how many tests are run';
807
+ };
808
+
809
+ subtest 'subtest with explicit done_testing()', sub {
810
+ ok 1, 'subtests with an explicit done testing should work';
811
+ ok 1, '... and support more than one test';
812
+ ok 1, '... no matter how many tests are run';
813
+ done_testing();
814
+ };
815
+
816
+ Extra arguments given to C<subtest> are passed to the callback. For example:
817
+
818
+ sub my_subtest {
819
+ my $range = shift;
820
+ ...
821
+ }
822
+
823
+ for my $range (1, 10, 100, 1000) {
824
+ subtest "testing range $range", \&my_subtest, $range;
825
+ }
826
+
827
+ =cut
828
+
829
+ sub subtest {
830
+ my $tb = Test::More->builder;
831
+ return $tb->subtest(@_);
832
+ }
833
+
834
+ =item B<pass>
835
+
836
+ =item B<fail>
837
+
838
+ pass($test_name);
839
+ fail($test_name);
840
+
841
+ Sometimes you just want to say that the tests have passed. Usually
842
+ the case is you've got some complicated condition that is difficult to
843
+ wedge into an C<ok()>. In this case, you can simply use C<pass()> (to
844
+ declare the test ok) or fail (for not ok). They are synonyms for
845
+ C<ok(1)> and C<ok(0)>.
846
+
847
+ Use these very, very, very sparingly.
848
+
849
+ =cut
850
+
851
+ sub pass (;$) {
852
+ my $tb = Test::More->builder;
853
+
854
+ return $tb->ok( 1, @_ );
855
+ }
856
+
857
+ sub fail (;$) {
858
+ my $tb = Test::More->builder;
859
+
860
+ return $tb->ok( 0, @_ );
861
+ }
862
+
863
+ =back
864
+
865
+
866
+ =head2 Module tests
867
+
868
+ Sometimes you want to test if a module, or a list of modules, can
869
+ successfully load. For example, you'll often want a first test which
870
+ simply loads all the modules in the distribution to make sure they
871
+ work before going on to do more complicated testing.
872
+
873
+ For such purposes we have C<use_ok> and C<require_ok>.
874
+
875
+ =over 4
876
+
877
+ =item B<require_ok>
878
+
879
+ require_ok($module);
880
+ require_ok($file);
881
+
882
+ Tries to C<require> the given $module or $file. If it loads
883
+ successfully, the test will pass. Otherwise it fails and displays the
884
+ load error.
885
+
886
+ C<require_ok> will guess whether the input is a module name or a
887
+ filename.
888
+
889
+ No exception will be thrown if the load fails.
890
+
891
+ # require Some::Module
892
+ require_ok "Some::Module";
893
+
894
+ # require "Some/File.pl";
895
+ require_ok "Some/File.pl";
896
+
897
+ # stop testing if any of your modules will not load
898
+ for my $module (@module) {
899
+ require_ok $module or BAIL_OUT "Can't load $module";
900
+ }
901
+
902
+ =cut
903
+
904
+ sub require_ok ($) {
905
+ my($module) = shift;
906
+ my $tb = Test::More->builder;
907
+
908
+ my $pack = caller;
909
+
910
+ # Try to determine if we've been given a module name or file.
911
+ # Module names must be barewords, files not.
912
+ $module = qq['$module'] unless _is_module_name($module);
913
+
914
+ my $code = <<REQUIRE;
915
+ package $pack;
916
+ require $module;
917
+ 1;
918
+ REQUIRE
919
+
920
+ my( $eval_result, $eval_error ) = _eval($code);
921
+ my $ok = $tb->ok( $eval_result, "require $module;" );
922
+
923
+ unless($ok) {
924
+ chomp $eval_error;
925
+ $tb->diag(<<DIAGNOSTIC);
926
+ Tried to require '$module'.
927
+ Error: $eval_error
928
+ DIAGNOSTIC
929
+
930
+ }
931
+
932
+ return $ok;
933
+ }
934
+
935
+ sub _is_module_name {
936
+ my $module = shift;
937
+
938
+ # Module names start with a letter.
939
+ # End with an alphanumeric.
940
+ # The rest is an alphanumeric or ::
941
+ $module =~ s/\b::\b//g;
942
+
943
+ return $module =~ /^[a-zA-Z]\w*$/ ? 1 : 0;
944
+ }
945
+
946
+
947
+ =item B<use_ok>
948
+
949
+ BEGIN { use_ok($module); }
950
+ BEGIN { use_ok($module, @imports); }
951
+
952
+ Like C<require_ok>, but it will C<use> the $module in question and
953
+ only loads modules, not files.
954
+
955
+ If you just want to test a module can be loaded, use C<require_ok>.
956
+
957
+ If you just want to load a module in a test, we recommend simply using
958
+ C<use> directly. It will cause the test to stop.
959
+
960
+ It's recommended that you run C<use_ok()> inside a BEGIN block so its
961
+ functions are exported at compile-time and prototypes are properly
962
+ honored.
963
+
964
+ If @imports are given, they are passed through to the use. So this:
965
+
966
+ BEGIN { use_ok('Some::Module', qw(foo bar)) }
967
+
968
+ is like doing this:
969
+
970
+ use Some::Module qw(foo bar);
971
+
972
+ Version numbers can be checked like so:
973
+
974
+ # Just like "use Some::Module 1.02"
975
+ BEGIN { use_ok('Some::Module', 1.02) }
976
+
977
+ Don't try to do this:
978
+
979
+ BEGIN {
980
+ use_ok('Some::Module');
981
+
982
+ ...some code that depends on the use...
983
+ ...happening at compile time...
984
+ }
985
+
986
+ because the notion of "compile-time" is relative. Instead, you want:
987
+
988
+ BEGIN { use_ok('Some::Module') }
989
+ BEGIN { ...some code that depends on the use... }
990
+
991
+ If you want the equivalent of C<use Foo ()>, use a module but not
992
+ import anything, use C<require_ok>.
993
+
994
+ BEGIN { require_ok "Foo" }
995
+
996
+ =cut
997
+
998
+ sub use_ok ($;@) {
999
+ my( $module, @imports ) = @_;
1000
+
1001
+ my $tb = Test::More->builder;
1002
+
1003
+ my %caller;
1004
+ @caller{qw/pack file line sub args want eval req strict warn/} = caller(0);
1005
+
1006
+ my ($pack, $filename, $line, $warn) = @caller{qw/pack file line warn/};
1007
+ $filename =~ y/\n\r/_/; # so it doesn't run off the "#line $line $f" line
1008
+
1009
+ my $code;
1010
+ if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) {
1011
+ # probably a version check. Perl needs to see the bare number
1012
+ # for it to work with non-Exporter based modules.
1013
+ $code = <<USE;
1014
+ package $pack;
1015
+ BEGIN { \${^WARNING_BITS} = \$args[-1] if defined \$args[-1] }
1016
+ #line $line $filename
1017
+ use $module $imports[0];
1018
+ 1;
1019
+ USE
1020
+ }
1021
+ else {
1022
+ $code = <<USE;
1023
+ package $pack;
1024
+ BEGIN { \${^WARNING_BITS} = \$args[-1] if defined \$args[-1] }
1025
+ #line $line $filename
1026
+ use $module \@{\$args[0]};
1027
+ 1;
1028
+ USE
1029
+ }
1030
+
1031
+ my ($eval_result, $eval_error) = _eval($code, \@imports, $warn);
1032
+ my $ok = $tb->ok( $eval_result, "use $module;" );
1033
+
1034
+ unless($ok) {
1035
+ chomp $eval_error;
1036
+ $@ =~ s{^BEGIN failed--compilation aborted at .*$}
1037
+ {BEGIN failed--compilation aborted at $filename line $line.}m;
1038
+ $tb->diag(<<DIAGNOSTIC);
1039
+ Tried to use '$module'.
1040
+ Error: $eval_error
1041
+ DIAGNOSTIC
1042
+
1043
+ }
1044
+
1045
+ return $ok;
1046
+ }
1047
+
1048
+ sub _eval {
1049
+ my( $code, @args ) = @_;
1050
+
1051
+ # Work around oddities surrounding resetting of $@ by immediately
1052
+ # storing it.
1053
+ my( $sigdie, $eval_result, $eval_error );
1054
+ {
1055
+ local( $@, $!, $SIG{__DIE__} ); # isolate eval
1056
+ $eval_result = eval $code; ## no critic (BuiltinFunctions::ProhibitStringyEval)
1057
+ $eval_error = $@;
1058
+ $sigdie = $SIG{__DIE__} || undef;
1059
+ }
1060
+ # make sure that $code got a chance to set $SIG{__DIE__}
1061
+ $SIG{__DIE__} = $sigdie if defined $sigdie;
1062
+
1063
+ return( $eval_result, $eval_error );
1064
+ }
1065
+
1066
+
1067
+ =back
1068
+
1069
+
1070
+ =head2 Complex data structures
1071
+
1072
+ Not everything is a simple eq check or regex. There are times you
1073
+ need to see if two data structures are equivalent. For these
1074
+ instances Test::More provides a handful of useful functions.
1075
+
1076
+ B<NOTE> I'm not quite sure what will happen with filehandles.
1077
+
1078
+ =over 4
1079
+
1080
+ =item B<is_deeply>
1081
+
1082
+ is_deeply( $got, $expected, $test_name );
1083
+
1084
+ Similar to C<is()>, except that if $got and $expected are references, it
1085
+ does a deep comparison walking each data structure to see if they are
1086
+ equivalent. If the two structures are different, it will display the
1087
+ place where they start differing.
1088
+
1089
+ C<is_deeply()> compares the dereferenced values of references, the
1090
+ references themselves (except for their type) are ignored. This means
1091
+ aspects such as blessing and ties are not considered "different".
1092
+
1093
+ C<is_deeply()> currently has very limited handling of function reference
1094
+ and globs. It merely checks if they have the same referent. This may
1095
+ improve in the future.
1096
+
1097
+ L<Test::Differences> and L<Test::Deep> provide more in-depth functionality
1098
+ along these lines.
1099
+
1100
+ B<NOTE> is_deeply() has limitations when it comes to comparing strings and
1101
+ refs:
1102
+
1103
+ my $path = path('.');
1104
+ my $hash = {};
1105
+ is_deeply( $path, "$path" ); # ok
1106
+ is_deeply( $hash, "$hash" ); # fail
1107
+
1108
+ This happens because is_deeply will unoverload all arguments unconditionally.
1109
+ It is probably best not to use is_deeply with overloading. For legacy reasons
1110
+ this is not likely to ever be fixed. If you would like a much better tool for
1111
+ this you should see L<Test2::Suite> Specifically L<Test2::Tools::Compare> has
1112
+ an C<is()> function that works like C<is_deeply> with many improvements.
1113
+
1114
+ =cut
1115
+
1116
+ our( @Data_Stack, %Refs_Seen );
1117
+ my $DNE = bless [], 'Does::Not::Exist';
1118
+
1119
+ sub _dne {
1120
+ return ref $_[0] eq ref $DNE;
1121
+ }
1122
+
1123
+ ## no critic (Subroutines::RequireArgUnpacking)
1124
+ sub is_deeply {
1125
+ my $tb = Test::More->builder;
1126
+
1127
+ unless( @_ == 2 or @_ == 3 ) {
1128
+ my $msg = <<'WARNING';
1129
+ is_deeply() takes two or three args, you gave %d.
1130
+ This usually means you passed an array or hash instead
1131
+ of a reference to it
1132
+ WARNING
1133
+ chop $msg; # clip off newline so carp() will put in line/file
1134
+
1135
+ _carp sprintf $msg, scalar @_;
1136
+
1137
+ return $tb->ok(0);
1138
+ }
1139
+
1140
+ my( $got, $expected, $name ) = @_;
1141
+
1142
+ $tb->_unoverload_str( \$expected, \$got );
1143
+
1144
+ my $ok;
1145
+ if( !ref $got and !ref $expected ) { # neither is a reference
1146
+ $ok = $tb->is_eq( $got, $expected, $name );
1147
+ }
1148
+ elsif( !ref $got xor !ref $expected ) { # one's a reference, one isn't
1149
+ $ok = $tb->ok( 0, $name );
1150
+ $tb->diag( _format_stack({ vals => [ $got, $expected ] }) );
1151
+ }
1152
+ else { # both references
1153
+ local @Data_Stack = ();
1154
+ if( _deep_check( $got, $expected ) ) {
1155
+ $ok = $tb->ok( 1, $name );
1156
+ }
1157
+ else {
1158
+ $ok = $tb->ok( 0, $name );
1159
+ $tb->diag( _format_stack(@Data_Stack) );
1160
+ }
1161
+ }
1162
+
1163
+ return $ok;
1164
+ }
1165
+
1166
+ sub _format_stack {
1167
+ my(@Stack) = @_;
1168
+
1169
+ my $var = '$FOO';
1170
+ my $did_arrow = 0;
1171
+ foreach my $entry (@Stack) {
1172
+ my $type = $entry->{type} || '';
1173
+ my $idx = $entry->{'idx'};
1174
+ if( $type eq 'HASH' ) {
1175
+ $var .= "->" unless $did_arrow++;
1176
+ $var .= "{$idx}";
1177
+ }
1178
+ elsif( $type eq 'ARRAY' ) {
1179
+ $var .= "->" unless $did_arrow++;
1180
+ $var .= "[$idx]";
1181
+ }
1182
+ elsif( $type eq 'REF' ) {
1183
+ $var = "\${$var}";
1184
+ }
1185
+ }
1186
+
1187
+ my @vals = @{ $Stack[-1]{vals} }[ 0, 1 ];
1188
+ my @vars;
1189
+ ( $vars[0] = $var ) =~ s/\$FOO/ \$got/;
1190
+ ( $vars[1] = $var ) =~ s/\$FOO/\$expected/;
1191
+
1192
+ my $out = "Structures begin differing at:\n";
1193
+ foreach my $idx ( 0 .. $#vals ) {
1194
+ my $val = $vals[$idx];
1195
+ $vals[$idx]
1196
+ = !defined $val ? 'undef'
1197
+ : _dne($val) ? "Does not exist"
1198
+ : ref $val ? "$val"
1199
+ : "'$val'";
1200
+ }
1201
+
1202
+ $out .= "$vars[0] = $vals[0]\n";
1203
+ $out .= "$vars[1] = $vals[1]\n";
1204
+
1205
+ $out =~ s/^/ /msg;
1206
+ return $out;
1207
+ }
1208
+
1209
+ my %_types = (
1210
+ (map +($_ => $_), qw(
1211
+ Regexp
1212
+ ARRAY
1213
+ HASH
1214
+ SCALAR
1215
+ REF
1216
+ GLOB
1217
+ CODE
1218
+ )),
1219
+ 'LVALUE' => 'SCALAR',
1220
+ 'REF' => 'SCALAR',
1221
+ 'VSTRING' => 'SCALAR',
1222
+ );
1223
+
1224
+ sub _type {
1225
+ my $thing = shift;
1226
+
1227
+ return '' if !ref $thing;
1228
+
1229
+ for my $type (keys %_types) {
1230
+ return $_types{$type} if UNIVERSAL::isa( $thing, $type );
1231
+ }
1232
+
1233
+ return '';
1234
+ }
1235
+
1236
+ =back
1237
+
1238
+
1239
+ =head2 Diagnostics
1240
+
1241
+ If you pick the right test function, you'll usually get a good idea of
1242
+ what went wrong when it failed. But sometimes it doesn't work out
1243
+ that way. So here we have ways for you to write your own diagnostic
1244
+ messages which are safer than just C<print STDERR>.
1245
+
1246
+ =over 4
1247
+
1248
+ =item B<diag>
1249
+
1250
+ diag(@diagnostic_message);
1251
+
1252
+ Prints a diagnostic message which is guaranteed not to interfere with
1253
+ test output. Like C<print> @diagnostic_message is simply concatenated
1254
+ together.
1255
+
1256
+ Returns false, so as to preserve failure.
1257
+
1258
+ Handy for this sort of thing:
1259
+
1260
+ ok( grep(/foo/, @users), "There's a foo user" ) or
1261
+ diag("Since there's no foo, check that /etc/bar is set up right");
1262
+
1263
+ which would produce:
1264
+
1265
+ not ok 42 - There's a foo user
1266
+ # Failed test 'There's a foo user'
1267
+ # in foo.t at line 52.
1268
+ # Since there's no foo, check that /etc/bar is set up right.
1269
+
1270
+ You might remember C<ok() or diag()> with the mnemonic C<open() or
1271
+ die()>.
1272
+
1273
+ B<NOTE> The exact formatting of the diagnostic output is still
1274
+ changing, but it is guaranteed that whatever you throw at it won't
1275
+ interfere with the test.
1276
+
1277
+ =item B<note>
1278
+
1279
+ note(@diagnostic_message);
1280
+
1281
+ Like C<diag()>, except the message will not be seen when the test is run
1282
+ in a harness. It will only be visible in the verbose TAP stream.
1283
+
1284
+ Handy for putting in notes which might be useful for debugging, but
1285
+ don't indicate a problem.
1286
+
1287
+ note("Tempfile is $tempfile");
1288
+
1289
+ =cut
1290
+
1291
+ sub diag {
1292
+ return Test::More->builder->diag(@_);
1293
+ }
1294
+
1295
+ sub note {
1296
+ return Test::More->builder->note(@_);
1297
+ }
1298
+
1299
+ =item B<explain>
1300
+
1301
+ my @dump = explain @diagnostic_message;
1302
+
1303
+ Will dump the contents of any references in a human readable format.
1304
+ Usually you want to pass this into C<note> or C<diag>.
1305
+
1306
+ Handy for things like...
1307
+
1308
+ is_deeply($have, $want) || diag explain $have;
1309
+
1310
+ or
1311
+
1312
+ note explain \%args;
1313
+ Some::Class->method(%args);
1314
+
1315
+ =cut
1316
+
1317
+ sub explain {
1318
+ return Test::More->builder->explain(@_);
1319
+ }
1320
+
1321
+ =back
1322
+
1323
+
1324
+ =head2 Conditional tests
1325
+
1326
+ Sometimes running a test under certain conditions will cause the
1327
+ test script to die. A certain function or method isn't implemented
1328
+ (such as C<fork()> on MacOS), some resource isn't available (like a
1329
+ net connection) or a module isn't available. In these cases it's
1330
+ necessary to skip tests, or declare that they are supposed to fail
1331
+ but will work in the future (a todo test).
1332
+
1333
+ For more details on the mechanics of skip and todo tests see
1334
+ L<Test::Harness>.
1335
+
1336
+ The way Test::More handles this is with a named block. Basically, a
1337
+ block of tests which can be skipped over or made todo. It's best if I
1338
+ just show you...
1339
+
1340
+ =over 4
1341
+
1342
+ =item B<SKIP: BLOCK>
1343
+
1344
+ SKIP: {
1345
+ skip $why, $how_many if $condition;
1346
+
1347
+ ...normal testing code goes here...
1348
+ }
1349
+
1350
+ This declares a block of tests that might be skipped, $how_many tests
1351
+ there are, $why and under what $condition to skip them. An example is
1352
+ the easiest way to illustrate:
1353
+
1354
+ SKIP: {
1355
+ eval { require HTML::Lint };
1356
+
1357
+ skip "HTML::Lint not installed", 2 if $@;
1358
+
1359
+ my $lint = new HTML::Lint;
1360
+ isa_ok( $lint, "HTML::Lint" );
1361
+
1362
+ $lint->parse( $html );
1363
+ is( $lint->errors, 0, "No errors found in HTML" );
1364
+ }
1365
+
1366
+ If the user does not have HTML::Lint installed, the whole block of
1367
+ code I<won't be run at all>. Test::More will output special ok's
1368
+ which Test::Harness interprets as skipped, but passing, tests.
1369
+
1370
+ It's important that $how_many accurately reflects the number of tests
1371
+ in the SKIP block so the # of tests run will match up with your plan.
1372
+ If your plan is C<no_plan> $how_many is optional and will default to 1.
1373
+
1374
+ It's perfectly safe to nest SKIP blocks. Each SKIP block must have
1375
+ the label C<SKIP>, or Test::More can't work its magic.
1376
+
1377
+ You don't skip tests which are failing because there's a bug in your
1378
+ program, or for which you don't yet have code written. For that you
1379
+ use TODO. Read on.
1380
+
1381
+ =cut
1382
+
1383
+ ## no critic (Subroutines::RequireFinalReturn)
1384
+ sub skip {
1385
+ my( $why, $how_many ) = @_;
1386
+ my $tb = Test::More->builder;
1387
+
1388
+ # If the plan is set, and is static, then skip needs a count. If the plan
1389
+ # is 'no_plan' we are fine. As well if plan is undefined then we are
1390
+ # waiting for done_testing.
1391
+ unless (defined $how_many) {
1392
+ my $plan = $tb->has_plan;
1393
+ _carp "skip() needs to know \$how_many tests are in the block"
1394
+ if $plan && $plan =~ m/^\d+$/;
1395
+ $how_many = 1;
1396
+ }
1397
+
1398
+ if( defined $how_many and $how_many =~ /\D/ ) {
1399
+ _carp
1400
+ "skip() was passed a non-numeric number of tests. Did you get the arguments backwards?";
1401
+ $how_many = 1;
1402
+ }
1403
+
1404
+ for( 1 .. $how_many ) {
1405
+ $tb->skip($why);
1406
+ }
1407
+
1408
+ no warnings 'exiting';
1409
+ last SKIP;
1410
+ }
1411
+
1412
+ =item B<TODO: BLOCK>
1413
+
1414
+ TODO: {
1415
+ local $TODO = $why if $condition;
1416
+
1417
+ ...normal testing code goes here...
1418
+ }
1419
+
1420
+ Declares a block of tests you expect to fail and $why. Perhaps it's
1421
+ because you haven't fixed a bug or haven't finished a new feature:
1422
+
1423
+ TODO: {
1424
+ local $TODO = "URI::Geller not finished";
1425
+
1426
+ my $card = "Eight of clubs";
1427
+ is( URI::Geller->your_card, $card, 'Is THIS your card?' );
1428
+
1429
+ my $spoon;
1430
+ URI::Geller->bend_spoon;
1431
+ is( $spoon, 'bent', "Spoon bending, that's original" );
1432
+ }
1433
+
1434
+ With a todo block, the tests inside are expected to fail. Test::More
1435
+ will run the tests normally, but print out special flags indicating
1436
+ they are "todo". L<Test::Harness> will interpret failures as being ok.
1437
+ Should anything succeed, it will report it as an unexpected success.
1438
+ You then know the thing you had todo is done and can remove the
1439
+ TODO flag.
1440
+
1441
+ The nice part about todo tests, as opposed to simply commenting out a
1442
+ block of tests, is that it is like having a programmatic todo list. You know
1443
+ how much work is left to be done, you're aware of what bugs there are,
1444
+ and you'll know immediately when they're fixed.
1445
+
1446
+ Once a todo test starts succeeding, simply move it outside the block.
1447
+ When the block is empty, delete it.
1448
+
1449
+ Note that, if you leave $TODO unset or undef, Test::More reports failures
1450
+ as normal. This can be useful to mark the tests as expected to fail only
1451
+ in certain conditions, e.g.:
1452
+
1453
+ TODO: {
1454
+ local $TODO = "$^O doesn't work yet. :(" if !_os_is_supported($^O);
1455
+
1456
+ ...
1457
+ }
1458
+
1459
+ =item B<todo_skip>
1460
+
1461
+ TODO: {
1462
+ todo_skip $why, $how_many if $condition;
1463
+
1464
+ ...normal testing code...
1465
+ }
1466
+
1467
+ With todo tests, it's best to have the tests actually run. That way
1468
+ you'll know when they start passing. Sometimes this isn't possible.
1469
+ Often a failing test will cause the whole program to die or hang, even
1470
+ inside an C<eval BLOCK> with and using C<alarm>. In these extreme
1471
+ cases you have no choice but to skip over the broken tests entirely.
1472
+
1473
+ The syntax and behavior is similar to a C<SKIP: BLOCK> except the
1474
+ tests will be marked as failing but todo. L<Test::Harness> will
1475
+ interpret them as passing.
1476
+
1477
+ =cut
1478
+
1479
+ sub todo_skip {
1480
+ my( $why, $how_many ) = @_;
1481
+ my $tb = Test::More->builder;
1482
+
1483
+ unless( defined $how_many ) {
1484
+ # $how_many can only be avoided when no_plan is in use.
1485
+ _carp "todo_skip() needs to know \$how_many tests are in the block"
1486
+ unless $tb->has_plan eq 'no_plan';
1487
+ $how_many = 1;
1488
+ }
1489
+
1490
+ for( 1 .. $how_many ) {
1491
+ $tb->todo_skip($why);
1492
+ }
1493
+
1494
+ no warnings 'exiting';
1495
+ last TODO;
1496
+ }
1497
+
1498
+ =item When do I use SKIP vs. TODO?
1499
+
1500
+ B<If it's something the user might not be able to do>, use SKIP.
1501
+ This includes optional modules that aren't installed, running under
1502
+ an OS that doesn't have some feature (like C<fork()> or symlinks), or maybe
1503
+ you need an Internet connection and one isn't available.
1504
+
1505
+ B<If it's something the programmer hasn't done yet>, use TODO. This
1506
+ is for any code you haven't written yet, or bugs you have yet to fix,
1507
+ but want to put tests in your testing script (always a good idea).
1508
+
1509
+
1510
+ =back
1511
+
1512
+
1513
+ =head2 Test control
1514
+
1515
+ =over 4
1516
+
1517
+ =item B<BAIL_OUT>
1518
+
1519
+ BAIL_OUT($reason);
1520
+
1521
+ Indicates to the harness that things are going so badly all testing
1522
+ should terminate. This includes the running of any additional test scripts.
1523
+
1524
+ This is typically used when testing cannot continue such as a critical
1525
+ module failing to compile or a necessary external utility not being
1526
+ available such as a database connection failing.
1527
+
1528
+ The test will exit with 255.
1529
+
1530
+ For even better control look at L<Test::Most>.
1531
+
1532
+ =cut
1533
+
1534
+ sub BAIL_OUT {
1535
+ my $reason = shift;
1536
+ my $tb = Test::More->builder;
1537
+
1538
+ $tb->BAIL_OUT($reason);
1539
+ }
1540
+
1541
+ =back
1542
+
1543
+
1544
+ =head2 Discouraged comparison functions
1545
+
1546
+ The use of the following functions is discouraged as they are not
1547
+ actually testing functions and produce no diagnostics to help figure
1548
+ out what went wrong. They were written before C<is_deeply()> existed
1549
+ because I couldn't figure out how to display a useful diff of two
1550
+ arbitrary data structures.
1551
+
1552
+ These functions are usually used inside an C<ok()>.
1553
+
1554
+ ok( eq_array(\@got, \@expected) );
1555
+
1556
+ C<is_deeply()> can do that better and with diagnostics.
1557
+
1558
+ is_deeply( \@got, \@expected );
1559
+
1560
+ They may be deprecated in future versions.
1561
+
1562
+ =over 4
1563
+
1564
+ =item B<eq_array>
1565
+
1566
+ my $is_eq = eq_array(\@got, \@expected);
1567
+
1568
+ Checks if two arrays are equivalent. This is a deep check, so
1569
+ multi-level structures are handled correctly.
1570
+
1571
+ =cut
1572
+
1573
+ #'#
1574
+ sub eq_array {
1575
+ local @Data_Stack = ();
1576
+ _deep_check(@_);
1577
+ }
1578
+
1579
+ sub _eq_array {
1580
+ my( $a1, $a2 ) = @_;
1581
+
1582
+ if( grep _type($_) ne 'ARRAY', $a1, $a2 ) {
1583
+ warn "eq_array passed a non-array ref";
1584
+ return 0;
1585
+ }
1586
+
1587
+ return 1 if $a1 eq $a2;
1588
+
1589
+ my $ok = 1;
1590
+ my $max = $#$a1 > $#$a2 ? $#$a1 : $#$a2;
1591
+ for( 0 .. $max ) {
1592
+ my $e1 = $_ > $#$a1 ? $DNE : $a1->[$_];
1593
+ my $e2 = $_ > $#$a2 ? $DNE : $a2->[$_];
1594
+
1595
+ next if _equal_nonrefs($e1, $e2);
1596
+
1597
+ push @Data_Stack, { type => 'ARRAY', idx => $_, vals => [ $e1, $e2 ] };
1598
+ $ok = _deep_check( $e1, $e2 );
1599
+ pop @Data_Stack if $ok;
1600
+
1601
+ last unless $ok;
1602
+ }
1603
+
1604
+ return $ok;
1605
+ }
1606
+
1607
+ sub _equal_nonrefs {
1608
+ my( $e1, $e2 ) = @_;
1609
+
1610
+ return if ref $e1 or ref $e2;
1611
+
1612
+ if ( defined $e1 ) {
1613
+ return 1 if defined $e2 and $e1 eq $e2;
1614
+ }
1615
+ else {
1616
+ return 1 if !defined $e2;
1617
+ }
1618
+
1619
+ return;
1620
+ }
1621
+
1622
+ sub _deep_check {
1623
+ my( $e1, $e2 ) = @_;
1624
+ my $tb = Test::More->builder;
1625
+
1626
+ my $ok = 0;
1627
+
1628
+ # Effectively turn %Refs_Seen into a stack. This avoids picking up
1629
+ # the same referenced used twice (such as [\$a, \$a]) to be considered
1630
+ # circular.
1631
+ local %Refs_Seen = %Refs_Seen;
1632
+
1633
+ {
1634
+ $tb->_unoverload_str( \$e1, \$e2 );
1635
+
1636
+ # Either they're both references or both not.
1637
+ my $same_ref = !( !ref $e1 xor !ref $e2 );
1638
+ my $not_ref = ( !ref $e1 and !ref $e2 );
1639
+
1640
+ if( defined $e1 xor defined $e2 ) {
1641
+ $ok = 0;
1642
+ }
1643
+ elsif( !defined $e1 and !defined $e2 ) {
1644
+ # Shortcut if they're both undefined.
1645
+ $ok = 1;
1646
+ }
1647
+ elsif( _dne($e1) xor _dne($e2) ) {
1648
+ $ok = 0;
1649
+ }
1650
+ elsif( $same_ref and( $e1 eq $e2 ) ) {
1651
+ $ok = 1;
1652
+ }
1653
+ elsif($not_ref) {
1654
+ push @Data_Stack, { type => '', vals => [ $e1, $e2 ] };
1655
+ $ok = 0;
1656
+ }
1657
+ else {
1658
+ if( $Refs_Seen{$e1} ) {
1659
+ return $Refs_Seen{$e1} eq $e2;
1660
+ }
1661
+ else {
1662
+ $Refs_Seen{$e1} = "$e2";
1663
+ }
1664
+
1665
+ my $type = _type($e1);
1666
+ $type = 'DIFFERENT' unless _type($e2) eq $type;
1667
+
1668
+ if( $type eq 'DIFFERENT' ) {
1669
+ push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
1670
+ $ok = 0;
1671
+ }
1672
+ elsif( $type eq 'ARRAY' ) {
1673
+ $ok = _eq_array( $e1, $e2 );
1674
+ }
1675
+ elsif( $type eq 'HASH' ) {
1676
+ $ok = _eq_hash( $e1, $e2 );
1677
+ }
1678
+ elsif( $type eq 'REF' ) {
1679
+ push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
1680
+ $ok = _deep_check( $$e1, $$e2 );
1681
+ pop @Data_Stack if $ok;
1682
+ }
1683
+ elsif( $type eq 'SCALAR' ) {
1684
+ push @Data_Stack, { type => 'REF', vals => [ $e1, $e2 ] };
1685
+ $ok = _deep_check( $$e1, $$e2 );
1686
+ pop @Data_Stack if $ok;
1687
+ }
1688
+ elsif($type) {
1689
+ push @Data_Stack, { type => $type, vals => [ $e1, $e2 ] };
1690
+ $ok = 0;
1691
+ }
1692
+ else {
1693
+ _whoa( 1, "No type in _deep_check" );
1694
+ }
1695
+ }
1696
+ }
1697
+
1698
+ return $ok;
1699
+ }
1700
+
1701
+ sub _whoa {
1702
+ my( $check, $desc ) = @_;
1703
+ if($check) {
1704
+ die <<"WHOA";
1705
+ WHOA! $desc
1706
+ This should never happen! Please contact the author immediately!
1707
+ WHOA
1708
+ }
1709
+ }
1710
+
1711
+ =item B<eq_hash>
1712
+
1713
+ my $is_eq = eq_hash(\%got, \%expected);
1714
+
1715
+ Determines if the two hashes contain the same keys and values. This
1716
+ is a deep check.
1717
+
1718
+ =cut
1719
+
1720
+ sub eq_hash {
1721
+ local @Data_Stack = ();
1722
+ return _deep_check(@_);
1723
+ }
1724
+
1725
+ sub _eq_hash {
1726
+ my( $a1, $a2 ) = @_;
1727
+
1728
+ if( grep _type($_) ne 'HASH', $a1, $a2 ) {
1729
+ warn "eq_hash passed a non-hash ref";
1730
+ return 0;
1731
+ }
1732
+
1733
+ return 1 if $a1 eq $a2;
1734
+
1735
+ my $ok = 1;
1736
+ my $bigger = keys %$a1 > keys %$a2 ? $a1 : $a2;
1737
+ foreach my $k ( keys %$bigger ) {
1738
+ my $e1 = exists $a1->{$k} ? $a1->{$k} : $DNE;
1739
+ my $e2 = exists $a2->{$k} ? $a2->{$k} : $DNE;
1740
+
1741
+ next if _equal_nonrefs($e1, $e2);
1742
+
1743
+ push @Data_Stack, { type => 'HASH', idx => $k, vals => [ $e1, $e2 ] };
1744
+ $ok = _deep_check( $e1, $e2 );
1745
+ pop @Data_Stack if $ok;
1746
+
1747
+ last unless $ok;
1748
+ }
1749
+
1750
+ return $ok;
1751
+ }
1752
+
1753
+ =item B<eq_set>
1754
+
1755
+ my $is_eq = eq_set(\@got, \@expected);
1756
+
1757
+ Similar to C<eq_array()>, except the order of the elements is B<not>
1758
+ important. This is a deep check, but the irrelevancy of order only
1759
+ applies to the top level.
1760
+
1761
+ ok( eq_set(\@got, \@expected) );
1762
+
1763
+ Is better written:
1764
+
1765
+ is_deeply( [sort @got], [sort @expected] );
1766
+
1767
+ B<NOTE> By historical accident, this is not a true set comparison.
1768
+ While the order of elements does not matter, duplicate elements do.
1769
+
1770
+ B<NOTE> C<eq_set()> does not know how to deal with references at the top
1771
+ level. The following is an example of a comparison which might not work:
1772
+
1773
+ eq_set([\1, \2], [\2, \1]);
1774
+
1775
+ L<Test::Deep> contains much better set comparison functions.
1776
+
1777
+ =cut
1778
+
1779
+ sub eq_set {
1780
+ my( $a1, $a2 ) = @_;
1781
+ return 0 unless @$a1 == @$a2;
1782
+
1783
+ no warnings 'uninitialized';
1784
+
1785
+ # It really doesn't matter how we sort them, as long as both arrays are
1786
+ # sorted with the same algorithm.
1787
+ #
1788
+ # Ensure that references are not accidentally treated the same as a
1789
+ # string containing the reference.
1790
+ #
1791
+ # Have to inline the sort routine due to a threading/sort bug.
1792
+ # See [rt.cpan.org 6782]
1793
+ #
1794
+ # I don't know how references would be sorted so we just don't sort
1795
+ # them. This means eq_set doesn't really work with refs.
1796
+ return eq_array(
1797
+ [ grep( ref, @$a1 ), sort( grep( !ref, @$a1 ) ) ],
1798
+ [ grep( ref, @$a2 ), sort( grep( !ref, @$a2 ) ) ],
1799
+ );
1800
+ }
1801
+
1802
+ =back
1803
+
1804
+
1805
+ =head2 Extending and Embedding Test::More
1806
+
1807
+ Sometimes the Test::More interface isn't quite enough. Fortunately,
1808
+ Test::More is built on top of L<Test::Builder> which provides a single,
1809
+ unified backend for any test library to use. This means two test
1810
+ libraries which both use L<Test::Builder> B<can> be used together in the
1811
+ same program.
1812
+
1813
+ If you simply want to do a little tweaking of how the tests behave,
1814
+ you can access the underlying L<Test::Builder> object like so:
1815
+
1816
+ =over 4
1817
+
1818
+ =item B<builder>
1819
+
1820
+ my $test_builder = Test::More->builder;
1821
+
1822
+ Returns the L<Test::Builder> object underlying Test::More for you to play
1823
+ with.
1824
+
1825
+
1826
+ =back
1827
+
1828
+
1829
+ =head1 EXIT CODES
1830
+
1831
+ If all your tests passed, L<Test::Builder> will exit with zero (which is
1832
+ normal). If anything failed it will exit with how many failed. If
1833
+ you run less (or more) tests than you planned, the missing (or extras)
1834
+ will be considered failures. If no tests were ever run L<Test::Builder>
1835
+ will throw a warning and exit with 255. If the test died, even after
1836
+ having successfully completed all its tests, it will still be
1837
+ considered a failure and will exit with 255.
1838
+
1839
+ So the exit codes are...
1840
+
1841
+ 0 all tests successful
1842
+ 255 test died or all passed but wrong # of tests run
1843
+ any other number how many failed (including missing or extras)
1844
+
1845
+ If you fail more than 254 tests, it will be reported as 254.
1846
+
1847
+ B<NOTE> This behavior may go away in future versions.
1848
+
1849
+
1850
+ =head1 COMPATIBILITY
1851
+
1852
+ Test::More works with Perls as old as 5.8.1.
1853
+
1854
+ Thread support is not very reliable before 5.10.1, but that's
1855
+ because threads are not very reliable before 5.10.1.
1856
+
1857
+ Although Test::More has been a core module in versions of Perl since 5.6.2, Test::More has evolved since then, and not all of the features you're used to will be present in the shipped version of Test::More. If you are writing a module, don't forget to indicate in your package metadata the minimum version of Test::More that you require. For instance, if you want to use C<done_testing()> but want your test script to run on Perl 5.10.0, you will need to explicitly require Test::More > 0.88.
1858
+
1859
+ Key feature milestones include:
1860
+
1861
+ =over 4
1862
+
1863
+ =item subtests
1864
+
1865
+ Subtests were released in Test::More 0.94, which came with Perl 5.12.0. Subtests did not implicitly call C<done_testing()> until 0.96; the first Perl with that fix was Perl 5.14.0 with 0.98.
1866
+
1867
+ =item C<done_testing()>
1868
+
1869
+ This was released in Test::More 0.88 and first shipped with Perl in 5.10.1 as part of Test::More 0.92.
1870
+
1871
+ =item C<cmp_ok()>
1872
+
1873
+ Although C<cmp_ok()> was introduced in 0.40, 0.86 fixed an important bug to make it safe for overloaded objects; the fixed first shipped with Perl in 5.10.1 as part of Test::More 0.92.
1874
+
1875
+ =item C<new_ok()> C<note()> and C<explain()>
1876
+
1877
+ These were was released in Test::More 0.82, and first shipped with Perl in 5.10.1 as part of Test::More 0.92.
1878
+
1879
+ =back
1880
+
1881
+ There is a full version history in the Changes file, and the Test::More versions included as core can be found using L<Module::CoreList>:
1882
+
1883
+ $ corelist -a Test::More
1884
+
1885
+
1886
+ =head1 CAVEATS and NOTES
1887
+
1888
+ =over 4
1889
+
1890
+ =item UTF-8 / "Wide character in print"
1891
+
1892
+ If you use UTF-8 or other non-ASCII characters with Test::More you
1893
+ might get a "Wide character in print" warning. Using
1894
+ C<< binmode STDOUT, ":utf8" >> will not fix it.
1895
+ L<Test::Builder> (which powers
1896
+ Test::More) duplicates STDOUT and STDERR. So any changes to them,
1897
+ including changing their output disciplines, will not be seen by
1898
+ Test::More.
1899
+
1900
+ One work around is to apply encodings to STDOUT and STDERR as early
1901
+ as possible and before Test::More (or any other Test module) loads.
1902
+
1903
+ use open ':std', ':encoding(UTF-8)';
1904
+ use Test::More;
1905
+
1906
+ A more direct work around is to change the filehandles used by
1907
+ L<Test::Builder>.
1908
+
1909
+ my $builder = Test::More->builder;
1910
+ binmode $builder->output, ":encoding(UTF-8)";
1911
+ binmode $builder->failure_output, ":encoding(UTF-8)";
1912
+ binmode $builder->todo_output, ":encoding(UTF-8)";
1913
+
1914
+
1915
+ =item Overloaded objects
1916
+
1917
+ String overloaded objects are compared B<as strings> (or in C<cmp_ok()>'s
1918
+ case, strings or numbers as appropriate to the comparison op). This
1919
+ prevents Test::More from piercing an object's interface allowing
1920
+ better blackbox testing. So if a function starts returning overloaded
1921
+ objects instead of bare strings your tests won't notice the
1922
+ difference. This is good.
1923
+
1924
+ However, it does mean that functions like C<is_deeply()> cannot be used to
1925
+ test the internals of string overloaded objects. In this case I would
1926
+ suggest L<Test::Deep> which contains more flexible testing functions for
1927
+ complex data structures.
1928
+
1929
+
1930
+ =item Threads
1931
+
1932
+ Test::More will only be aware of threads if C<use threads> has been done
1933
+ I<before> Test::More is loaded. This is ok:
1934
+
1935
+ use threads;
1936
+ use Test::More;
1937
+
1938
+ This may cause problems:
1939
+
1940
+ use Test::More
1941
+ use threads;
1942
+
1943
+ 5.8.1 and above are supported. Anything below that has too many bugs.
1944
+
1945
+ =back
1946
+
1947
+
1948
+ =head1 HISTORY
1949
+
1950
+ This is a case of convergent evolution with Joshua Pritikin's L<Test>
1951
+ module. I was largely unaware of its existence when I'd first
1952
+ written my own C<ok()> routines. This module exists because I can't
1953
+ figure out how to easily wedge test names into Test's interface (along
1954
+ with a few other problems).
1955
+
1956
+ The goal here is to have a testing utility that's simple to learn,
1957
+ quick to use and difficult to trip yourself up with while still
1958
+ providing more flexibility than the existing Test.pm. As such, the
1959
+ names of the most common routines are kept tiny, special cases and
1960
+ magic side-effects are kept to a minimum. WYSIWYG.
1961
+
1962
+
1963
+ =head1 SEE ALSO
1964
+
1965
+ =head2
1966
+
1967
+ =head2 ALTERNATIVES
1968
+
1969
+ L<Test2::Suite> is the most recent and modern set of tools for testing.
1970
+
1971
+ L<Test::Simple> if all this confuses you and you just want to write
1972
+ some tests. You can upgrade to Test::More later (it's forward
1973
+ compatible).
1974
+
1975
+ L<Test::Legacy> tests written with Test.pm, the original testing
1976
+ module, do not play well with other testing libraries. Test::Legacy
1977
+ emulates the Test.pm interface and does play well with others.
1978
+
1979
+ =head2 ADDITIONAL LIBRARIES
1980
+
1981
+ L<Test::Differences> for more ways to test complex data structures.
1982
+ And it plays well with Test::More.
1983
+
1984
+ L<Test::Class> is like xUnit but more perlish.
1985
+
1986
+ L<Test::Deep> gives you more powerful complex data structure testing.
1987
+
1988
+ L<Test::Inline> shows the idea of embedded testing.
1989
+
1990
+ L<Mock::Quick> The ultimate mocking library. Easily spawn objects defined on
1991
+ the fly. Can also override, block, or reimplement packages as needed.
1992
+
1993
+ L<Test::FixtureBuilder> Quickly define fixture data for unit tests.
1994
+
1995
+ =head2 OTHER COMPONENTS
1996
+
1997
+ L<Test::Harness> is the test runner and output interpreter for Perl.
1998
+ It's the thing that powers C<make test> and where the C<prove> utility
1999
+ comes from.
2000
+
2001
+ =head2 BUNDLES
2002
+
2003
+ L<Test::Most> Most commonly needed test functions and features.
2004
+
2005
+ =head1 ENVIRONMENT VARIABLES
2006
+
2007
+ See L<Test2::Env> for a list of meaningul environment variables.
2008
+
2009
+ =head1 AUTHORS
2010
+
2011
+ Michael G Schwern E<lt>schwern@pobox.comE<gt> with much inspiration
2012
+ from Joshua Pritikin's Test module and lots of help from Barrie
2013
+ Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and
2014
+ the perl-qa gang.
2015
+
2016
+ =head1 MAINTAINERS
2017
+
2018
+ =over 4
2019
+
2020
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2021
+
2022
+ =back
2023
+
2024
+
2025
+ =head1 BUGS
2026
+
2027
+ See L<https://github.com/Test-More/test-more/issues> to report and view bugs.
2028
+
2029
+
2030
+ =head1 SOURCE
2031
+
2032
+ The source code repository for Test::More can be found at
2033
+ L<https://github.com/Test-More/test-more/>.
2034
+
2035
+
2036
+ =head1 COPYRIGHT
2037
+
2038
+ Copyright 2001-2008 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2039
+
2040
+ This program is free software; you can redistribute it and/or
2041
+ modify it under the same terms as Perl itself.
2042
+
2043
+ See L<https://dev.perl.org/licenses/>
2044
+
2045
+ =cut
2046
+
2047
+ 1;
git/usr/share/perl5/core_perl/Test/Simple.pm ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test::Simple;
2
+
3
+ use 5.006;
4
+
5
+ use strict;
6
+
7
+ our $VERSION = '1.302210';
8
+
9
+ use Test::Builder::Module;
10
+ our @ISA = qw(Test::Builder::Module);
11
+ our @EXPORT = qw(ok);
12
+
13
+ my $CLASS = __PACKAGE__;
14
+
15
+ =head1 NAME
16
+
17
+ Test::Simple - Basic utilities for writing tests.
18
+
19
+ =head1 SYNOPSIS
20
+
21
+ use Test::Simple tests => 1;
22
+
23
+ ok( $foo eq $bar, 'foo is bar' );
24
+
25
+
26
+ =head1 DESCRIPTION
27
+
28
+ ** If you are unfamiliar with testing B<read L<Test::Tutorial> first!> **
29
+
30
+ This is an extremely simple, extremely basic module for writing tests
31
+ suitable for CPAN modules and other pursuits. If you wish to do more
32
+ complicated testing, use the Test::More module (a drop-in replacement
33
+ for this one).
34
+
35
+ The basic unit of Perl testing is the ok. For each thing you want to
36
+ test your program will print out an "ok" or "not ok" to indicate pass
37
+ or fail. You do this with the C<ok()> function (see below).
38
+
39
+ The only other constraint is you must pre-declare how many tests you
40
+ plan to run. This is in case something goes horribly wrong during the
41
+ test and your test program aborts, or skips a test or whatever. You
42
+ do this like so:
43
+
44
+ use Test::Simple tests => 23;
45
+
46
+ You must have a plan.
47
+
48
+
49
+ =over 4
50
+
51
+ =item B<ok>
52
+
53
+ ok( $foo eq $bar, $name );
54
+ ok( $foo eq $bar );
55
+
56
+ C<ok()> is given an expression (in this case C<$foo eq $bar>). If it's
57
+ true, the test passed. If it's false, it didn't. That's about it.
58
+
59
+ C<ok()> prints out either "ok" or "not ok" along with a test number (it
60
+ keeps track of that for you).
61
+
62
+ # This produces "ok 1 - Hell not yet frozen over" (or not ok)
63
+ ok( get_temperature($hell) > 0, 'Hell not yet frozen over' );
64
+
65
+ If you provide a $name, that will be printed along with the "ok/not
66
+ ok" to make it easier to find your test when if fails (just search for
67
+ the name). It also makes it easier for the next guy to understand
68
+ what your test is for. It's highly recommended you use test names.
69
+
70
+ All tests are run in scalar context. So this:
71
+
72
+ ok( @stuff, 'I have some stuff' );
73
+
74
+ will do what you mean (fail if stuff is empty)
75
+
76
+ =cut
77
+
78
+ sub ok ($;$) { ## no critic (Subroutines::ProhibitSubroutinePrototypes)
79
+ return $CLASS->builder->ok(@_);
80
+ }
81
+
82
+ =back
83
+
84
+ Test::Simple will start by printing number of tests run in the form
85
+ "1..M" (so "1..5" means you're going to run 5 tests). This strange
86
+ format lets L<Test::Harness> know how many tests you plan on running in
87
+ case something goes horribly wrong.
88
+
89
+ If all your tests passed, Test::Simple will exit with zero (which is
90
+ normal). If anything failed it will exit with how many failed. If
91
+ you run less (or more) tests than you planned, the missing (or extras)
92
+ will be considered failures. If no tests were ever run Test::Simple
93
+ will throw a warning and exit with 255. If the test died, even after
94
+ having successfully completed all its tests, it will still be
95
+ considered a failure and will exit with 255.
96
+
97
+ So the exit codes are...
98
+
99
+ 0 all tests successful
100
+ 255 test died or all passed but wrong # of tests run
101
+ any other number how many failed (including missing or extras)
102
+
103
+ If you fail more than 254 tests, it will be reported as 254.
104
+
105
+ This module is by no means trying to be a complete testing system.
106
+ It's just to get you started. Once you're off the ground its
107
+ recommended you look at L<Test::More>.
108
+
109
+
110
+ =head1 EXAMPLE
111
+
112
+ Here's an example of a simple .t file for the fictional Film module.
113
+
114
+ use Test::Simple tests => 5;
115
+
116
+ use Film; # What you're testing.
117
+
118
+ my $btaste = Film->new({ Title => 'Bad Taste',
119
+ Director => 'Peter Jackson',
120
+ Rating => 'R',
121
+ NumExplodingSheep => 1
122
+ });
123
+ ok( defined($btaste) && ref $btaste eq 'Film', 'new() works' );
124
+
125
+ ok( $btaste->Title eq 'Bad Taste', 'Title() get' );
126
+ ok( $btaste->Director eq 'Peter Jackson', 'Director() get' );
127
+ ok( $btaste->Rating eq 'R', 'Rating() get' );
128
+ ok( $btaste->NumExplodingSheep == 1, 'NumExplodingSheep() get' );
129
+
130
+ It will produce output like this:
131
+
132
+ 1..5
133
+ ok 1 - new() works
134
+ ok 2 - Title() get
135
+ ok 3 - Director() get
136
+ not ok 4 - Rating() get
137
+ # Failed test 'Rating() get'
138
+ # in t/film.t at line 14.
139
+ ok 5 - NumExplodingSheep() get
140
+ # Looks like you failed 1 tests of 5
141
+
142
+ Indicating the Film::Rating() method is broken.
143
+
144
+
145
+ =head1 CAVEATS
146
+
147
+ Test::Simple will only report a maximum of 254 failures in its exit
148
+ code. If this is a problem, you probably have a huge test script.
149
+ Split it into multiple files. (Otherwise blame the Unix folks for
150
+ using an unsigned short integer as the exit status).
151
+
152
+ Because VMS's exit codes are much, much different than the rest of the
153
+ universe, and perl does horrible mangling to them that gets in my way,
154
+ it works like this on VMS.
155
+
156
+ 0 SS$_NORMAL all tests successful
157
+ 4 SS$_ABORT something went wrong
158
+
159
+ Unfortunately, I can't differentiate any further.
160
+
161
+
162
+ =head1 NOTES
163
+
164
+ Test::Simple is B<explicitly> tested all the way back to perl 5.6.0.
165
+
166
+ Test::Simple is thread-safe in perl 5.8.1 and up.
167
+
168
+ =head1 HISTORY
169
+
170
+ This module was conceived while talking with Tony Bowden in his
171
+ kitchen one night about the problems I was having writing some really
172
+ complicated feature into the new Testing module. He observed that the
173
+ main problem is not dealing with these edge cases but that people hate
174
+ to write tests B<at all>. What was needed was a dead simple module
175
+ that took all the hard work out of testing and was really, really easy
176
+ to learn. Paul Johnson simultaneously had this idea (unfortunately,
177
+ he wasn't in Tony's kitchen). This is it.
178
+
179
+
180
+ =head1 SEE ALSO
181
+
182
+ =over 4
183
+
184
+ =item L<Test::More>
185
+
186
+ More testing functions! Once you outgrow Test::Simple, look at
187
+ L<Test::More>. Test::Simple is 100% forward compatible with L<Test::More>
188
+ (i.e. you can just use L<Test::More> instead of Test::Simple in your
189
+ programs and things will still work).
190
+
191
+ =back
192
+
193
+ Look in L<Test::More>'s SEE ALSO for more testing modules.
194
+
195
+
196
+ =head1 AUTHORS
197
+
198
+ Idea by Tony Bowden and Paul Johnson, code by Michael G Schwern
199
+ E<lt>schwern@pobox.comE<gt>, wardrobe by Calvin Klein.
200
+
201
+ =head1 MAINTAINERS
202
+
203
+ =over 4
204
+
205
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
206
+
207
+ =back
208
+
209
+ =head1 COPYRIGHT
210
+
211
+ Copyright 2001-2008 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
212
+
213
+ This program is free software; you can redistribute it and/or
214
+ modify it under the same terms as Perl itself.
215
+
216
+ See L<https://dev.perl.org/licenses/>
217
+
218
+ =cut
219
+
220
+ 1;
git/usr/share/perl5/core_perl/Test/Tester.pm ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use strict;
2
+
3
+ package Test::Tester;
4
+
5
+ BEGIN
6
+ {
7
+ if (*Test::Builder::new{CODE})
8
+ {
9
+ warn "You should load Test::Tester before Test::Builder (or anything that loads Test::Builder)"
10
+ }
11
+ }
12
+
13
+ use Test::Builder;
14
+ use Test::Tester::CaptureRunner;
15
+ use Test::Tester::Delegate;
16
+
17
+ require Exporter;
18
+
19
+ our $VERSION = '1.302210';
20
+
21
+ our @EXPORT = qw( run_tests check_tests check_test cmp_results show_space );
22
+ our @ISA = qw( Exporter );
23
+
24
+ my $Test = Test::Builder->new;
25
+ my $Capture = Test::Tester::Capture->new;
26
+ my $Delegator = Test::Tester::Delegate->new;
27
+ $Delegator->{Object} = $Test;
28
+
29
+ my $runner = Test::Tester::CaptureRunner->new;
30
+
31
+ my $want_space = $ENV{TESTTESTERSPACE};
32
+
33
+ sub show_space
34
+ {
35
+ $want_space = 1;
36
+ }
37
+
38
+ my $colour = '';
39
+ my $reset = '';
40
+
41
+ if (my $want_colour = $ENV{TESTTESTERCOLOUR} || $ENV{TESTTESTERCOLOR})
42
+ {
43
+ if (eval { require Term::ANSIColor; 1 })
44
+ {
45
+ eval { require Win32::Console::ANSI } if 'MSWin32' eq $^O; # support color on windows platforms
46
+ my ($f, $b) = split(",", $want_colour);
47
+ $colour = Term::ANSIColor::color($f).Term::ANSIColor::color("on_$b");
48
+ $reset = Term::ANSIColor::color("reset");
49
+ }
50
+
51
+ }
52
+
53
+ sub new_new
54
+ {
55
+ return $Delegator;
56
+ }
57
+
58
+ sub capture
59
+ {
60
+ return Test::Tester::Capture->new;
61
+ }
62
+
63
+ sub fh
64
+ {
65
+ # experiment with capturing output, I don't like it
66
+ $runner = Test::Tester::FHRunner->new;
67
+
68
+ return $Test;
69
+ }
70
+
71
+ sub find_run_tests
72
+ {
73
+ my $d = 1;
74
+ my $found = 0;
75
+ while ((not $found) and (my ($sub) = (caller($d))[3]) )
76
+ {
77
+ # print "$d: $sub\n";
78
+ $found = ($sub eq "Test::Tester::run_tests");
79
+ $d++;
80
+ }
81
+
82
+ # die "Didn't find 'run_tests' in caller stack" unless $found;
83
+ return $d;
84
+ }
85
+
86
+ sub run_tests
87
+ {
88
+ local($Delegator->{Object}) = $Capture;
89
+
90
+ $runner->run_tests(@_);
91
+
92
+ return ($runner->get_premature, $runner->get_results);
93
+ }
94
+
95
+ sub check_test
96
+ {
97
+ my $test = shift;
98
+ my $expect = shift;
99
+ my $name = shift;
100
+ $name = "" unless defined($name);
101
+
102
+ @_ = ($test, [$expect], $name);
103
+ goto &check_tests;
104
+ }
105
+
106
+ sub check_tests
107
+ {
108
+ my $test = shift;
109
+ my $expects = shift;
110
+ my $name = shift;
111
+ $name = "" unless defined($name);
112
+
113
+ my ($prem, @results) = eval { run_tests($test, $name) };
114
+
115
+ $Test->ok(! $@, "Test '$name' completed") || $Test->diag($@);
116
+ $Test->ok(! length($prem), "Test '$name' no premature diagnostication") ||
117
+ $Test->diag("Before any testing anything, your tests said\n$prem");
118
+
119
+ local $Test::Builder::Level = $Test::Builder::Level + 1;
120
+ cmp_results(\@results, $expects, $name);
121
+ return ($prem, @results);
122
+ }
123
+
124
+ sub cmp_field
125
+ {
126
+ my ($result, $expect, $field, $desc) = @_;
127
+
128
+ if (defined $expect->{$field})
129
+ {
130
+ $Test->is_eq($result->{$field}, $expect->{$field},
131
+ "$desc compare $field");
132
+ }
133
+ }
134
+
135
+ sub cmp_result
136
+ {
137
+ my ($result, $expect, $name) = @_;
138
+
139
+ my $sub_name = $result->{name};
140
+ $sub_name = "" unless defined($name);
141
+
142
+ my $desc = "subtest '$sub_name' of '$name'";
143
+
144
+ {
145
+ local $Test::Builder::Level = $Test::Builder::Level + 1;
146
+
147
+ cmp_field($result, $expect, "ok", $desc);
148
+
149
+ cmp_field($result, $expect, "actual_ok", $desc);
150
+
151
+ cmp_field($result, $expect, "type", $desc);
152
+
153
+ cmp_field($result, $expect, "reason", $desc);
154
+
155
+ cmp_field($result, $expect, "name", $desc);
156
+ }
157
+
158
+ # if we got no depth then default to 1
159
+ my $depth = 1;
160
+ if (exists $expect->{depth})
161
+ {
162
+ $depth = $expect->{depth};
163
+ }
164
+
165
+ # if depth was explicitly undef then don't test it
166
+ if (defined $depth)
167
+ {
168
+ $Test->is_eq($result->{depth}, $depth, "checking depth") ||
169
+ $Test->diag('You need to change $Test::Builder::Level');
170
+ }
171
+
172
+ if (defined(my $exp = $expect->{diag}))
173
+ {
174
+
175
+ my $got = '';
176
+ if (ref $exp eq 'Regexp') {
177
+
178
+ if (not $Test->like($result->{diag}, $exp,
179
+ "subtest '$sub_name' of '$name' compare diag"))
180
+ {
181
+ $got = $result->{diag};
182
+ }
183
+
184
+ } else {
185
+
186
+ # if there actually is some diag then put a \n on the end if it's not
187
+ # there already
188
+ $exp .= "\n" if (length($exp) and $exp !~ /\n$/);
189
+
190
+ if (not $Test->ok($result->{diag} eq $exp,
191
+ "subtest '$sub_name' of '$name' compare diag"))
192
+ {
193
+ $got = $result->{diag};
194
+ }
195
+ }
196
+
197
+ if ($got) {
198
+ my $glen = length($got);
199
+ my $elen = length($exp);
200
+ for ($got, $exp)
201
+ {
202
+ my @lines = split("\n", $_);
203
+ $_ = join("\n", map {
204
+ if ($want_space)
205
+ {
206
+ $_ = $colour.escape($_).$reset;
207
+ }
208
+ else
209
+ {
210
+ "'$colour$_$reset'"
211
+ }
212
+ } @lines);
213
+ }
214
+
215
+ $Test->diag(<<EOM);
216
+ Got diag ($glen bytes):
217
+ $got
218
+ Expected diag ($elen bytes):
219
+ $exp
220
+ EOM
221
+ }
222
+ }
223
+ }
224
+
225
+ sub escape
226
+ {
227
+ my $str = shift;
228
+ my $res = '';
229
+ for my $char (split("", $str))
230
+ {
231
+ my $c = ord($char);
232
+ if(($c>32 and $c<125) or $c == 10)
233
+ {
234
+ $res .= $char;
235
+ }
236
+ else
237
+ {
238
+ $res .= sprintf('\x{%x}', $c)
239
+ }
240
+ }
241
+ return $res;
242
+ }
243
+
244
+ sub cmp_results
245
+ {
246
+ my ($results, $expects, $name) = @_;
247
+
248
+ $Test->is_num(scalar @$results, scalar @$expects, "Test '$name' result count");
249
+
250
+ for (my $i = 0; $i < @$expects; $i++)
251
+ {
252
+ my $expect = $expects->[$i];
253
+ my $result = $results->[$i];
254
+
255
+ local $Test::Builder::Level = $Test::Builder::Level + 1;
256
+ cmp_result($result, $expect, $name);
257
+ }
258
+ }
259
+
260
+ ######## nicked from Test::More
261
+ sub plan {
262
+ my(@plan) = @_;
263
+
264
+ my $caller = caller;
265
+
266
+ $Test->exported_to($caller);
267
+
268
+ my @imports = ();
269
+ foreach my $idx (0..$#plan) {
270
+ if( $plan[$idx] eq 'import' ) {
271
+ my($tag, $imports) = splice @plan, $idx, 2;
272
+ @imports = @$imports;
273
+ last;
274
+ }
275
+ }
276
+
277
+ $Test->plan(@plan);
278
+
279
+ __PACKAGE__->_export_to_level(1, __PACKAGE__, @imports);
280
+ }
281
+
282
+ sub import {
283
+ my($class) = shift;
284
+ {
285
+ no warnings 'redefine';
286
+ *Test::Builder::new = \&new_new;
287
+ }
288
+ goto &plan;
289
+ }
290
+
291
+ sub _export_to_level
292
+ {
293
+ my $pkg = shift;
294
+ my $level = shift;
295
+ (undef) = shift; # redundant arg
296
+ my $callpkg = caller($level);
297
+ $pkg->export($callpkg, @_);
298
+ }
299
+
300
+
301
+ ############
302
+
303
+ 1;
304
+
305
+ __END__
306
+
307
+ =head1 NAME
308
+
309
+ Test::Tester - Ease testing test modules built with Test::Builder
310
+
311
+ =head1 SYNOPSIS
312
+
313
+ use Test::Tester tests => 6;
314
+
315
+ use Test::MyStyle;
316
+
317
+ check_test(
318
+ sub {
319
+ is_mystyle_eq("this", "that", "not eq");
320
+ },
321
+ {
322
+ ok => 0, # expect this to fail
323
+ name => "not eq",
324
+ diag => "Expected: 'this'\nGot: 'that'",
325
+ }
326
+ );
327
+
328
+ or
329
+
330
+ use Test::Tester tests => 6;
331
+
332
+ use Test::MyStyle;
333
+
334
+ check_test(
335
+ sub {
336
+ is_mystyle_qr("this", "that", "not matching");
337
+ },
338
+ {
339
+ ok => 0, # expect this to fail
340
+ name => "not matching",
341
+ diag => qr/Expected: 'this'\s+Got: 'that'/,
342
+ }
343
+ );
344
+
345
+ or
346
+
347
+ use Test::Tester;
348
+
349
+ use Test::More tests => 3;
350
+ use Test::MyStyle;
351
+
352
+ my ($premature, @results) = run_tests(
353
+ sub {
354
+ is_database_alive("dbname");
355
+ }
356
+ );
357
+
358
+ # now use Test::More::like to check the diagnostic output
359
+
360
+ like($results[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag");
361
+
362
+ =head1 DESCRIPTION
363
+
364
+ If you have written a test module based on Test::Builder then Test::Tester
365
+ allows you to test it with the minimum of effort.
366
+
367
+ =head1 HOW TO USE (THE EASY WAY)
368
+
369
+ From version 0.08 Test::Tester no longer requires you to included anything
370
+ special in your test modules. All you need to do is
371
+
372
+ use Test::Tester;
373
+
374
+ in your test script B<before> any other Test::Builder based modules and away
375
+ you go.
376
+
377
+ Other modules based on Test::Builder can be used to help with the
378
+ testing. In fact you can even use functions from your module to test
379
+ other functions from the same module (while this is possible it is
380
+ probably not a good idea, if your module has bugs, then
381
+ using it to test itself may give the wrong answers).
382
+
383
+ The easiest way to test is to do something like
384
+
385
+ check_test(
386
+ sub { is_mystyle_eq("this", "that", "not eq") },
387
+ {
388
+ ok => 0, # we expect the test to fail
389
+ name => "not eq",
390
+ diag => "Expected: 'this'\nGot: 'that'",
391
+ }
392
+ );
393
+
394
+ this will execute the is_mystyle_eq test, capturing its results and
395
+ checking that they are what was expected.
396
+
397
+ You may need to examine the test results in a more flexible way, for
398
+ example, the diagnostic output may be quite long or complex or it may involve
399
+ something that you cannot predict in advance like a timestamp. In this case
400
+ you can get direct access to the test results:
401
+
402
+ my ($premature, @results) = run_tests(
403
+ sub {
404
+ is_database_alive("dbname");
405
+ }
406
+ );
407
+
408
+ like($result[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag");
409
+
410
+ or
411
+
412
+ check_test(
413
+ sub { is_mystyle_qr("this", "that", "not matching") },
414
+ {
415
+ ok => 0, # we expect the test to fail
416
+ name => "not matching",
417
+ diag => qr/Expected: 'this'\s+Got: 'that'/,
418
+ }
419
+ );
420
+
421
+ We cannot predict how long the database ping will take so we use
422
+ Test::More's like() test to check that the diagnostic string is of the right
423
+ form.
424
+
425
+ =head1 HOW TO USE (THE HARD WAY)
426
+
427
+ I<This is here for backwards compatibility only>
428
+
429
+ Make your module use the Test::Tester::Capture object instead of the
430
+ Test::Builder one. How to do this depends on your module but assuming that
431
+ your module holds the Test::Builder object in $Test and that all your test
432
+ routines access it through $Test then providing a function something like this
433
+
434
+ sub set_builder
435
+ {
436
+ $Test = shift;
437
+ }
438
+
439
+ should allow your test scripts to do
440
+
441
+ Test::YourModule::set_builder(Test::Tester->capture);
442
+
443
+ and after that any tests inside your module will captured.
444
+
445
+ =head1 TEST RESULTS
446
+
447
+ The result of each test is captured in a hash. These hashes are the same as
448
+ the hashes returned by Test::Builder->details but with a couple of extra
449
+ fields.
450
+
451
+ These fields are documented in L<Test::Builder> in the details() function
452
+
453
+ =over 2
454
+
455
+ =item ok
456
+
457
+ Did the test pass?
458
+
459
+ =item actual_ok
460
+
461
+ Did the test really pass? That is, did the pass come from
462
+ Test::Builder->ok() or did it pass because it was a TODO test?
463
+
464
+ =item name
465
+
466
+ The name supplied for the test.
467
+
468
+ =item type
469
+
470
+ What kind of test? Possibilities include, skip, todo etc. See
471
+ L<Test::Builder> for more details.
472
+
473
+ =item reason
474
+
475
+ The reason for the skip, todo etc. See L<Test::Builder> for more details.
476
+
477
+ =back
478
+
479
+ These fields are exclusive to Test::Tester.
480
+
481
+ =over 2
482
+
483
+ =item diag
484
+
485
+ Any diagnostics that were output for the test. This only includes
486
+ diagnostics output B<after> the test result is declared.
487
+
488
+ Note that Test::Builder ensures that any diagnostics end in a \n and
489
+ it in earlier versions of Test::Tester it was essential that you have
490
+ the final \n in your expected diagnostics. From version 0.10 onward,
491
+ Test::Tester will add the \n if you forgot it. It will not add a \n if
492
+ you are expecting no diagnostics. See below for help tracking down
493
+ hard to find space and tab related problems.
494
+
495
+ =item depth
496
+
497
+ This allows you to check that your test module is setting the correct value
498
+ for $Test::Builder::Level and thus giving the correct file and line number
499
+ when a test fails. It is calculated by looking at caller() and
500
+ $Test::Builder::Level. It should count how many subroutines there are before
501
+ jumping into the function you are testing. So for example in
502
+
503
+ run_tests( sub { my_test_function("a", "b") } );
504
+
505
+ the depth should be 1 and in
506
+
507
+ sub deeper { my_test_function("a", "b") }
508
+
509
+ run_tests(sub { deeper() });
510
+
511
+ depth should be 2, that is 1 for the sub {} and one for deeper(). This
512
+ might seem a little complex but if your tests look like the simple
513
+ examples in this doc then you don't need to worry as the depth will
514
+ always be 1 and that's what Test::Tester expects by default.
515
+
516
+ B<Note>: if you do not specify a value for depth in check_test() then it
517
+ automatically compares it against 1, if you really want to skip the depth
518
+ test then pass in undef.
519
+
520
+ B<Note>: depth will not be correctly calculated for tests that run from a
521
+ signal handler or an END block or anywhere else that hides the call stack.
522
+
523
+ =back
524
+
525
+ Some of Test::Tester's functions return arrays of these hashes, just
526
+ like Test::Builder->details. That is, the hash for the first test will
527
+ be array element 1 (not 0). Element 0 will not be a hash it will be a
528
+ string which contains any diagnostic output that came before the first
529
+ test. This should usually be empty, if it's not, it means something
530
+ output diagnostics before any test results showed up.
531
+
532
+ =head1 SPACES AND TABS
533
+
534
+ Appearances can be deceptive, especially when it comes to emptiness. If you
535
+ are scratching your head trying to work out why Test::Tester is saying that
536
+ your diagnostics are wrong when they look perfectly right then the answer is
537
+ probably whitespace. From version 0.10 on, Test::Tester surrounds the
538
+ expected and got diag values with single quotes to make it easier to spot
539
+ trailing whitespace. So in this example
540
+
541
+ # Got diag (5 bytes):
542
+ # 'abcd '
543
+ # Expected diag (4 bytes):
544
+ # 'abcd'
545
+
546
+ it is quite clear that there is a space at the end of the first string.
547
+ Another way to solve this problem is to use colour and inverse video on an
548
+ ANSI terminal, see below COLOUR below if you want this.
549
+
550
+ Unfortunately this is sometimes not enough, neither colour nor quotes will
551
+ help you with problems involving tabs, other non-printing characters and
552
+ certain kinds of problems inherent in Unicode. To deal with this, you can
553
+ switch Test::Tester into a mode whereby all "tricky" characters are shown as
554
+ \{xx}. Tricky characters are those with ASCII code less than 33 or higher
555
+ than 126. This makes the output more difficult to read but much easier to
556
+ find subtle differences between strings. To turn on this mode either call
557
+ C<show_space()> in your test script or set the C<TESTTESTERSPACE> environment
558
+ variable to be a true value. The example above would then look like
559
+
560
+ # Got diag (5 bytes):
561
+ # abcd\x{20}
562
+ # Expected diag (4 bytes):
563
+ # abcd
564
+
565
+ =head1 COLOUR
566
+
567
+ If you prefer to use colour as a means of finding tricky whitespace
568
+ characters then you can set the C<TESTTESTCOLOUR> environment variable to a
569
+ comma separated pair of colours, the first for the foreground, the second
570
+ for the background. For example "white,red" will print white text on a red
571
+ background. This requires the Term::ANSIColor module. You can specify any
572
+ colour that would be acceptable to the Term::ANSIColor::color function.
573
+
574
+ If you spell colour differently, that's no problem. The C<TESTTESTERCOLOR>
575
+ variable also works (if both are set then the British spelling wins out).
576
+
577
+ =head1 EXPORTED FUNCTIONS
578
+
579
+ =head3 ($premature, @results) = run_tests(\&test_sub)
580
+
581
+ \&test_sub is a reference to a subroutine.
582
+
583
+ run_tests runs the subroutine in $test_sub and captures the results of any
584
+ tests inside it. You can run more than 1 test inside this subroutine if you
585
+ like.
586
+
587
+ $premature is a string containing any diagnostic output from before
588
+ the first test.
589
+
590
+ @results is an array of test result hashes.
591
+
592
+ =head3 cmp_result(\%result, \%expect, $name)
593
+
594
+ \%result is a ref to a test result hash.
595
+
596
+ \%expect is a ref to a hash of expected values for the test result.
597
+
598
+ cmp_result compares the result with the expected values. If any differences
599
+ are found it outputs diagnostics. You may leave out any field from the
600
+ expected result and cmp_result will not do the comparison of that field.
601
+
602
+ =head3 cmp_results(\@results, \@expects, $name)
603
+
604
+ \@results is a ref to an array of test results.
605
+
606
+ \@expects is a ref to an array of hash refs.
607
+
608
+ cmp_results checks that the results match the expected results and if any
609
+ differences are found it outputs diagnostics. It first checks that the
610
+ number of elements in \@results and \@expects is the same. Then it goes
611
+ through each result checking it against the expected result as in
612
+ cmp_result() above.
613
+
614
+ =head3 ($premature, @results) = check_tests(\&test_sub, \@expects, $name)
615
+
616
+ \&test_sub is a reference to a subroutine.
617
+
618
+ \@expect is a ref to an array of hash refs which are expected test results.
619
+
620
+ check_tests combines run_tests and cmp_tests into a single call. It also
621
+ checks if the tests died at any stage.
622
+
623
+ It returns the same values as run_tests, so you can further examine the test
624
+ results if you need to.
625
+
626
+ =head3 ($premature, @results) = check_test(\&test_sub, \%expect, $name)
627
+
628
+ \&test_sub is a reference to a subroutine.
629
+
630
+ \%expect is a ref to an hash of expected values for the test result.
631
+
632
+ check_test is a wrapper around check_tests. It combines run_tests and
633
+ cmp_tests into a single call, checking if the test died. It assumes
634
+ that only a single test is run inside \&test_sub and include a test to
635
+ make sure this is true.
636
+
637
+ It returns the same values as run_tests, so you can further examine the test
638
+ results if you need to.
639
+
640
+ =head3 show_space()
641
+
642
+ Turn on the escaping of characters as described in the SPACES AND TABS
643
+ section.
644
+
645
+ =head1 HOW IT WORKS
646
+
647
+ Normally, a test module (let's call it Test:MyStyle) calls
648
+ Test::Builder->new to get the Test::Builder object. Test::MyStyle calls
649
+ methods on this object to record information about test results. When
650
+ Test::Tester is loaded, it replaces Test::Builder's new() method with one
651
+ which returns a Test::Tester::Delegate object. Most of the time this object
652
+ behaves as the real Test::Builder object. Any methods that are called are
653
+ delegated to the real Test::Builder object so everything works perfectly.
654
+ However once we go into test mode, the method calls are no longer passed to
655
+ the real Test::Builder object, instead they go to the Test::Tester::Capture
656
+ object. This object seems exactly like the real Test::Builder object,
657
+ except, instead of outputting test results and diagnostics, it just records
658
+ all the information for later analysis.
659
+
660
+ =head1 CAVEATS
661
+
662
+ Support for calling Test::Builder->note is minimal. It's implemented
663
+ as an empty stub, so modules that use it will not crash but the calls
664
+ are not recorded for testing purposes like the others. Patches
665
+ welcome.
666
+
667
+ =head1 SEE ALSO
668
+
669
+ L<Test::Builder> the source of testing goodness. L<Test::Builder::Tester>
670
+ for an alternative approach to the problem tackled by Test::Tester -
671
+ captures the strings output by Test::Builder. This means you cannot get
672
+ separate access to the individual pieces of information and you must predict
673
+ B<exactly> what your test will output.
674
+
675
+ =head1 AUTHOR
676
+
677
+ This module is copyright 2005 Fergal Daly <fergal@esatclear.ie>, some parts
678
+ are based on other people's work.
679
+
680
+ Plan handling lifted from Test::More. written by Michael G Schwern
681
+ <schwern@pobox.com>.
682
+
683
+ Test::Tester::Capture is a cut down and hacked up version of Test::Builder.
684
+ Test::Builder was written by chromatic <chromatic@wgz.org> and Michael G
685
+ Schwern <schwern@pobox.com>.
686
+
687
+ =head1 LICENSE
688
+
689
+ Under the same license as Perl itself
690
+
691
+ See L<https://dev.perl.org/licenses/>
692
+
693
+ =cut
git/usr/share/perl5/core_perl/Test2/API.pm ADDED
@@ -0,0 +1,1785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::API;
2
+ use strict;
3
+ use warnings;
4
+
5
+ use Time::HiRes qw/time/;
6
+ use Test2::Util qw/USE_THREADS/;
7
+
8
+ BEGIN {
9
+ $ENV{TEST_ACTIVE} ||= 1;
10
+ $ENV{TEST2_ACTIVE} = 1;
11
+ }
12
+
13
+ our $VERSION = '1.302210';
14
+
15
+
16
+ my $INST;
17
+ my $ENDING = 0;
18
+ sub test2_unset_is_end { $ENDING = 0 }
19
+ sub test2_get_is_end { $ENDING }
20
+
21
+ sub test2_set_is_end {
22
+ my $before = $ENDING;
23
+ ($ENDING) = @_ ? @_ : (1);
24
+
25
+ # Only send the event in a transition from false to true
26
+ return if $before;
27
+ return unless $ENDING;
28
+
29
+ return unless $INST;
30
+ my $stack = $INST->stack or return;
31
+ my $root = $stack->root or return;
32
+
33
+ return unless $root->count;
34
+
35
+ return unless $$ == $INST->pid;
36
+ return unless get_tid() == $INST->tid;
37
+
38
+ my $trace = Test2::EventFacet::Trace->new(
39
+ frame => [__PACKAGE__, __FILE__, __LINE__, __PACKAGE__ . '::test2_set_is_end'],
40
+ );
41
+ my $ctx = Test2::API::Context->new(
42
+ trace => $trace,
43
+ hub => $root,
44
+ );
45
+
46
+ $ctx->send_ev2(control => { phase => 'END', details => 'Transition to END phase' });
47
+
48
+ 1;
49
+ }
50
+
51
+ use Test2::API::Instance(\$INST);
52
+
53
+ # Set the exit status
54
+ END {
55
+ test2_set_is_end(); # See gh #16
56
+ $INST->set_exit();
57
+ }
58
+
59
+ sub CLONE {
60
+ my $init = test2_init_done();
61
+ my $load = test2_load_done();
62
+
63
+ return if $init && $load;
64
+
65
+ require Carp;
66
+ Carp::croak "Test2 must be fully loaded before you start a new thread!\n";
67
+ }
68
+
69
+ # See gh #16
70
+ {
71
+ no warnings;
72
+ INIT { eval 'END { test2_set_is_end() }; 1' or die $@ }
73
+ }
74
+
75
+ BEGIN {
76
+ no warnings 'once';
77
+ if("$]" >= 5.014 || $ENV{T2_CHECK_DEPTH} || $Test2::API::DO_DEPTH_CHECK) {
78
+ *DO_DEPTH_CHECK = sub() { 1 };
79
+ }
80
+ else {
81
+ *DO_DEPTH_CHECK = sub() { 0 };
82
+ }
83
+ }
84
+
85
+ use Test2::EventFacet::Trace();
86
+ use Test2::Util::Trace(); # Legacy
87
+
88
+ use Test2::Hub::Subtest();
89
+ use Test2::Hub::Interceptor();
90
+ use Test2::Hub::Interceptor::Terminator();
91
+
92
+ use Test2::Event::Ok();
93
+ use Test2::Event::Diag();
94
+ use Test2::Event::Note();
95
+ use Test2::Event::Plan();
96
+ use Test2::Event::Bail();
97
+ use Test2::Event::Exception();
98
+ use Test2::Event::Waiting();
99
+ use Test2::Event::Skip();
100
+ use Test2::Event::Subtest();
101
+
102
+ use Carp qw/carp croak confess/;
103
+ use Scalar::Util qw/blessed weaken/;
104
+ use Test2::Util qw/get_tid clone_io pkg_to_file gen_uid/;
105
+
106
+ our @EXPORT_OK = qw{
107
+ context release
108
+ context_do
109
+ no_context
110
+ intercept intercept_deep
111
+ run_subtest
112
+
113
+ test2_init_done
114
+ test2_load_done
115
+ test2_load
116
+ test2_start_preload
117
+ test2_stop_preload
118
+ test2_in_preload
119
+ test2_is_testing_done
120
+
121
+ test2_set_is_end
122
+ test2_unset_is_end
123
+ test2_get_is_end
124
+
125
+ test2_pid
126
+ test2_tid
127
+ test2_stack
128
+ test2_no_wait
129
+ test2_ipc_wait_enable
130
+ test2_ipc_wait_disable
131
+ test2_ipc_wait_enabled
132
+
133
+ test2_add_uuid_via
134
+
135
+ test2_add_callback_testing_done
136
+
137
+ test2_add_callback_context_aquire
138
+ test2_add_callback_context_acquire
139
+ test2_add_callback_context_init
140
+ test2_add_callback_context_release
141
+ test2_add_callback_exit
142
+ test2_add_callback_post_load
143
+ test2_add_callback_pre_subtest
144
+ test2_list_context_aquire_callbacks
145
+ test2_list_context_acquire_callbacks
146
+ test2_list_context_init_callbacks
147
+ test2_list_context_release_callbacks
148
+ test2_list_exit_callbacks
149
+ test2_list_post_load_callbacks
150
+ test2_list_pre_subtest_callbacks
151
+
152
+ test2_ipc
153
+ test2_has_ipc
154
+ test2_ipc_disable
155
+ test2_ipc_disabled
156
+ test2_ipc_drivers
157
+ test2_ipc_add_driver
158
+ test2_ipc_polling
159
+ test2_ipc_disable_polling
160
+ test2_ipc_enable_polling
161
+ test2_ipc_get_pending
162
+ test2_ipc_set_pending
163
+ test2_ipc_get_timeout
164
+ test2_ipc_set_timeout
165
+
166
+ test2_formatter
167
+ test2_formatters
168
+ test2_formatter_add
169
+ test2_formatter_set
170
+
171
+ test2_stdout
172
+ test2_stderr
173
+ test2_reset_io
174
+
175
+ test2_enable_trace_stamps
176
+ test2_disable_trace_stamps
177
+ test2_trace_stamps_enabled
178
+
179
+ test2_add_pending_diag
180
+ test2_get_pending_diags
181
+ test2_clear_pending_diags
182
+ };
183
+ BEGIN { require Exporter; our @ISA = qw(Exporter) }
184
+
185
+ my @PENDING_DIAGS;
186
+
187
+ sub test2_add_pending_diag { push @PENDING_DIAGS => @_ }
188
+ sub test2_get_pending_diags { @PENDING_DIAGS }
189
+ sub test2_clear_pending_diags { my @out = @PENDING_DIAGS; @PENDING_DIAGS = (); return @out }
190
+
191
+ my $STACK = $INST->stack;
192
+ my $CONTEXTS = $INST->contexts;
193
+ my $INIT_CBS = $INST->context_init_callbacks;
194
+ my $ACQUIRE_CBS = $INST->context_acquire_callbacks;
195
+
196
+ my $STDOUT = clone_io(\*STDOUT);
197
+ my $STDERR = clone_io(\*STDERR);
198
+ sub test2_stdout { $STDOUT ||= clone_io(\*STDOUT) }
199
+ sub test2_stderr { $STDERR ||= clone_io(\*STDERR) }
200
+
201
+ sub test2_post_preload_reset {
202
+ test2_reset_io();
203
+ $INST->post_preload_reset;
204
+ }
205
+
206
+ sub test2_reset_io {
207
+ $STDOUT = clone_io(\*STDOUT);
208
+ $STDERR = clone_io(\*STDERR);
209
+ }
210
+
211
+ sub test2_init_done { $INST->finalized }
212
+ sub test2_load_done { $INST->loaded }
213
+
214
+ sub test2_load { $INST->load }
215
+ sub test2_start_preload { $ENV{T2_IN_PRELOAD} = 1; $INST->start_preload }
216
+ sub test2_stop_preload { $ENV{T2_IN_PRELOAD} = 0; $INST->stop_preload }
217
+ sub test2_in_preload { $INST->preload }
218
+
219
+ sub test2_pid { $INST->pid }
220
+ sub test2_tid { $INST->tid }
221
+ sub test2_stack { $INST->stack }
222
+ sub test2_ipc_wait_enable { $INST->set_no_wait(0) }
223
+ sub test2_ipc_wait_disable { $INST->set_no_wait(1) }
224
+ sub test2_ipc_wait_enabled { !$INST->no_wait }
225
+
226
+ sub test2_enable_trace_stamps { $INST->test2_enable_trace_stamps }
227
+ sub test2_disable_trace_stamps { $INST->test2_disable_trace_stamps }
228
+ sub test2_trace_stamps_enabled { $INST->test2_trace_stamps_enabled }
229
+
230
+ sub test2_is_testing_done {
231
+ # No instance? VERY DONE!
232
+ return 1 unless $INST;
233
+
234
+ # No stack? tests must be done, it is created pretty early
235
+ my $stack = $INST->stack or return 1;
236
+
237
+ # Nothing on the stack, no root hub yet, likely have not started testing
238
+ return 0 unless @$stack;
239
+
240
+ # Stack has a slot for the root hub (see above) but it is undefined, likely
241
+ # garbage collected, test is done
242
+ my $root_hub = $stack->[0] or return 1;
243
+
244
+ # If the root hub is ended than testing is done.
245
+ return 1 if $root_hub->ended;
246
+
247
+ # Looks like we are still testing!
248
+ return 0;
249
+ }
250
+
251
+ sub test2_no_wait {
252
+ $INST->set_no_wait(@_) if @_;
253
+ $INST->no_wait;
254
+ }
255
+
256
+ sub test2_add_callback_testing_done {
257
+ my $cb = shift;
258
+
259
+ test2_add_callback_post_load(sub {
260
+ my $stack = test2_stack();
261
+ $stack->top; # Ensure we have a hub
262
+ my ($hub) = Test2::API::test2_stack->all;
263
+
264
+ $hub->set_active(1);
265
+
266
+ $hub->follow_up($cb);
267
+ });
268
+
269
+ return;
270
+ }
271
+
272
+ sub test2_add_callback_context_acquire { $INST->add_context_acquire_callback(@_) }
273
+ sub test2_add_callback_context_aquire { $INST->add_context_acquire_callback(@_) }
274
+ sub test2_add_callback_context_init { $INST->add_context_init_callback(@_) }
275
+ sub test2_add_callback_context_release { $INST->add_context_release_callback(@_) }
276
+ sub test2_add_callback_exit { $INST->add_exit_callback(@_) }
277
+ sub test2_add_callback_post_load { $INST->add_post_load_callback(@_) }
278
+ sub test2_add_callback_pre_subtest { $INST->add_pre_subtest_callback(@_) }
279
+ sub test2_list_context_aquire_callbacks { @{$INST->context_acquire_callbacks} }
280
+ sub test2_list_context_acquire_callbacks { @{$INST->context_acquire_callbacks} }
281
+ sub test2_list_context_init_callbacks { @{$INST->context_init_callbacks} }
282
+ sub test2_list_context_release_callbacks { @{$INST->context_release_callbacks} }
283
+ sub test2_list_exit_callbacks { @{$INST->exit_callbacks} }
284
+ sub test2_list_post_load_callbacks { @{$INST->post_load_callbacks} }
285
+ sub test2_list_pre_subtest_callbacks { @{$INST->pre_subtest_callbacks} }
286
+
287
+ sub test2_add_uuid_via {
288
+ $INST->set_add_uuid_via(@_) if @_;
289
+ $INST->add_uuid_via();
290
+ }
291
+
292
+ sub test2_ipc { $INST->ipc }
293
+ sub test2_has_ipc { $INST->has_ipc }
294
+ sub test2_ipc_disable { $INST->ipc_disable }
295
+ sub test2_ipc_disabled { $INST->ipc_disabled }
296
+ sub test2_ipc_add_driver { $INST->add_ipc_driver(@_) }
297
+ sub test2_ipc_drivers { @{$INST->ipc_drivers} }
298
+ sub test2_ipc_polling { $INST->ipc_polling }
299
+ sub test2_ipc_enable_polling { $INST->enable_ipc_polling }
300
+ sub test2_ipc_disable_polling { $INST->disable_ipc_polling }
301
+ sub test2_ipc_get_pending { $INST->get_ipc_pending }
302
+ sub test2_ipc_set_pending { $INST->set_ipc_pending(@_) }
303
+ sub test2_ipc_set_timeout { $INST->set_ipc_timeout(@_) }
304
+ sub test2_ipc_get_timeout { $INST->ipc_timeout() }
305
+ sub test2_ipc_enable_shm { 0 }
306
+
307
+ sub test2_formatter {
308
+ if ($ENV{T2_FORMATTER} && $ENV{T2_FORMATTER} =~ m/^(\+)?(.*)$/) {
309
+ my $formatter = $1 ? $2 : "Test2::Formatter::$2";
310
+ my $file = pkg_to_file($formatter);
311
+ require $file;
312
+ return $formatter;
313
+ }
314
+
315
+ return $INST->formatter;
316
+ }
317
+
318
+ sub test2_formatters { @{$INST->formatters} }
319
+ sub test2_formatter_add { $INST->add_formatter(@_) }
320
+ sub test2_formatter_set {
321
+ my ($formatter) = @_;
322
+ croak "No formatter specified" unless $formatter;
323
+ croak "Global Formatter already set" if $INST->formatter_set;
324
+ $INST->set_formatter($formatter);
325
+ }
326
+
327
+ # Private, for use in Test2::API::Context
328
+ sub _contexts_ref { $INST->contexts }
329
+ sub _context_acquire_callbacks_ref { $INST->context_acquire_callbacks }
330
+ sub _context_init_callbacks_ref { $INST->context_init_callbacks }
331
+ sub _context_release_callbacks_ref { $INST->context_release_callbacks }
332
+ sub _add_uuid_via_ref { \($INST->{Test2::API::Instance::ADD_UUID_VIA()}) }
333
+
334
+ # Private, for use in Test2::IPC
335
+ sub _set_ipc { $INST->set_ipc(@_) }
336
+
337
+ sub context_do(&;@) {
338
+ my $code = shift;
339
+ my @args = @_;
340
+
341
+ my $ctx = context(level => 1);
342
+
343
+ my $want = wantarray;
344
+
345
+ my @out;
346
+ my $ok = eval {
347
+ $want ? @out = $code->($ctx, @args) :
348
+ defined($want) ? $out[0] = $code->($ctx, @args) :
349
+ $code->($ctx, @args) ;
350
+ 1;
351
+ };
352
+ my $err = $@;
353
+
354
+ $ctx->release;
355
+
356
+ die $err unless $ok;
357
+
358
+ return @out if $want;
359
+ return $out[0] if defined $want;
360
+ return;
361
+ }
362
+
363
+ sub no_context(&;$) {
364
+ my ($code, $hid) = @_;
365
+ $hid ||= $STACK->top->hid;
366
+
367
+ my $ctx = $CONTEXTS->{$hid};
368
+ delete $CONTEXTS->{$hid};
369
+ my $ok = eval { $code->(); 1 };
370
+ my $err = $@;
371
+
372
+ $CONTEXTS->{$hid} = $ctx;
373
+ weaken($CONTEXTS->{$hid});
374
+
375
+ die $err unless $ok;
376
+
377
+ return;
378
+ };
379
+
380
+ my $UUID_VIA = _add_uuid_via_ref();
381
+ sub context {
382
+ # We need to grab these before anything else to ensure they are not
383
+ # changed.
384
+ my ($errno, $eval_error, $child_error, $extended_error) = (0 + $!, $@, $?, $^E);
385
+
386
+ my %params = (level => 0, wrapped => 0, @_);
387
+
388
+ # If something is getting a context then the sync system needs to be
389
+ # considered loaded...
390
+ $INST->load unless $INST->{loaded};
391
+
392
+ croak "context() called, but return value is ignored"
393
+ unless defined wantarray;
394
+
395
+ my $stack = $params{stack} || $STACK;
396
+ my $hub = $params{hub} || (@$stack ? $stack->[-1] : $stack->top);
397
+
398
+ # Catch an edge case where we try to get context after the root hub has
399
+ # been garbage collected resulting in a stack that has a single undef
400
+ # hub
401
+ if (!($hub && $hub->{hid}) && !exists($params{hub}) && @$stack) {
402
+ my $msg;
403
+
404
+ if ($hub && !$hub->{hid}) {
405
+ $msg = Carp::longmess("$hub has no hid! (did you attempt a testing event after done_testing?). You may be relying on a tool or plugin that was based off an old Test2 that did not require hids.");
406
+ }
407
+ else {
408
+ $msg = Carp::longmess("Attempt to get Test2 context after testing has completed (did you attempt a testing event after done_testing?)");
409
+ }
410
+
411
+ # The error message is usually masked by the global destruction, so we have to print to STDER
412
+ print STDERR $msg;
413
+
414
+ # Make sure this is a failure, we are probably already in END, so set $? to change the exit code
415
+ $? = 1;
416
+
417
+ # Now we actually die to interrupt the program flow and avoid undefined his warnings
418
+ die $msg;
419
+ }
420
+
421
+ my $hid = $hub->{hid};
422
+ my $current = $CONTEXTS->{$hid};
423
+
424
+ $_->(\%params) for @$ACQUIRE_CBS;
425
+ map $_->(\%params), @{$hub->{_context_acquire}} if $hub->{_context_acquire};
426
+
427
+ # This is for https://github.com/Test-More/test-more/issues/16
428
+ # and https://rt.perl.org/Public/Bug/Display.html?id=127774
429
+ my $phase = ${^GLOBAL_PHASE} || 'NA';
430
+ my $end_phase = $ENDING || $phase eq 'END' || $phase eq 'DESTRUCT';
431
+
432
+ my $level = 1 + $params{level};
433
+ my ($pkg, $file, $line, $sub, @other) = $end_phase ? caller(0) : caller($level);
434
+ unless ($pkg || $end_phase) {
435
+ confess "Could not find context at depth $level" unless $params{fudge};
436
+ ($pkg, $file, $line, $sub, @other) = caller(--$level) while ($level >= 0 && !$pkg);
437
+ }
438
+
439
+ my $depth = $level;
440
+ $depth++ while DO_DEPTH_CHECK && !$end_phase && (!$current || $depth <= $current->{_depth} + $params{wrapped}) && caller($depth + 1);
441
+ $depth -= $params{wrapped};
442
+ my $depth_ok = !DO_DEPTH_CHECK || $end_phase || !$current || $current->{_depth} < $depth;
443
+
444
+ if ($current && $params{on_release} && $depth_ok) {
445
+ $current->{_on_release} ||= [];
446
+ push @{$current->{_on_release}} => $params{on_release};
447
+ }
448
+
449
+ # I know this is ugly....
450
+ ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error) and return bless(
451
+ {
452
+ %$current,
453
+ _is_canon => undef,
454
+ errno => $errno,
455
+ eval_error => $eval_error,
456
+ child_error => $child_error,
457
+ _is_spawn => [$pkg, $file, $line, $sub],
458
+ _start_fail_count => $hub->{failed} || 0,
459
+ },
460
+ 'Test2::API::Context'
461
+ ) if $current && $depth_ok;
462
+
463
+ # Handle error condition of bad level
464
+ if ($current) {
465
+ unless (${$current->{_aborted}}) {
466
+ _canon_error($current, [$pkg, $file, $line, $sub, $depth])
467
+ unless $current->{_is_canon};
468
+
469
+ _depth_error($current, [$pkg, $file, $line, $sub, $depth])
470
+ unless $depth_ok;
471
+ }
472
+
473
+ $current->release if $current->{_is_canon};
474
+
475
+ delete $CONTEXTS->{$hid};
476
+ }
477
+
478
+ # Directly bless the object here, calling new is a noticeable performance
479
+ # hit with how often this needs to be called.
480
+ my $trace = bless(
481
+ {
482
+ frame => [$pkg, $file, $line, $sub],
483
+ pid => $$,
484
+ tid => get_tid(),
485
+ cid => gen_uid(),
486
+ hid => $hid,
487
+ nested => $hub->{nested},
488
+ buffered => $hub->{buffered},
489
+
490
+ full_caller => [$pkg, $file, $line, $sub, @other],
491
+
492
+ $INST->{trace_stamps} ? (stamp => time()) : (),
493
+
494
+ $$UUID_VIA ? (
495
+ huuid => $hub->{uuid},
496
+ uuid => ${$UUID_VIA}->('context'),
497
+ ) : (),
498
+ },
499
+ 'Test2::EventFacet::Trace'
500
+ );
501
+
502
+ # Directly bless the object here, calling new is a noticeable performance
503
+ # hit with how often this needs to be called.
504
+ my $aborted = 0;
505
+ $current = bless(
506
+ {
507
+ _aborted => \$aborted,
508
+ stack => $stack,
509
+ hub => $hub,
510
+ trace => $trace,
511
+ _is_canon => 1,
512
+ _depth => $depth,
513
+ errno => $errno,
514
+ eval_error => $eval_error,
515
+ child_error => $child_error,
516
+ _start_fail_count => $hub->{failed} || 0,
517
+ $params{on_release} ? (_on_release => [$params{on_release}]) : (),
518
+ },
519
+ 'Test2::API::Context'
520
+ );
521
+
522
+ $CONTEXTS->{$hid} = $current;
523
+ weaken($CONTEXTS->{$hid});
524
+
525
+ $_->($current) for @$INIT_CBS;
526
+ map $_->($current), @{$hub->{_context_init}} if $hub->{_context_init};
527
+
528
+ $params{on_init}->($current) if $params{on_init};
529
+
530
+ ($!, $@, $?, $^E) = ($errno, $eval_error, $child_error, $extended_error);
531
+
532
+ return $current;
533
+ }
534
+
535
+ sub _depth_error {
536
+ _existing_error(@_, <<" EOT");
537
+ context() was called to retrieve an existing context, however the existing
538
+ context was created in a stack frame at the same, or deeper level. This usually
539
+ means that a tool failed to release the context when it was finished.
540
+ EOT
541
+ }
542
+
543
+ sub _canon_error {
544
+ _existing_error(@_, <<" EOT");
545
+ context() was called to retrieve an existing context, however the existing
546
+ context has an invalid internal state (!_canon_count). This should not normally
547
+ happen unless something is mucking about with internals...
548
+ EOT
549
+ }
550
+
551
+ sub _existing_error {
552
+ my ($ctx, $details, $msg) = @_;
553
+ my ($pkg, $file, $line, $sub, $depth) = @$details;
554
+
555
+ my $oldframe = $ctx->{trace}->frame;
556
+ my $olddepth = $ctx->{_depth};
557
+
558
+ # Older versions of Carp do not export longmess() function, so it needs to be called with package name
559
+ my $mess = Carp::longmess();
560
+
561
+ warn <<" EOT";
562
+ $msg
563
+ Old context details:
564
+ File: $oldframe->[1]
565
+ Line: $oldframe->[2]
566
+ Tool: $oldframe->[3]
567
+ Depth: $olddepth
568
+
569
+ New context details:
570
+ File: $file
571
+ Line: $line
572
+ Tool: $sub
573
+ Depth: $depth
574
+
575
+ Trace: $mess
576
+
577
+ Removing the old context and creating a new one...
578
+ EOT
579
+ }
580
+
581
+ sub release($;$) {
582
+ $_[0]->release;
583
+ return $_[1];
584
+ }
585
+
586
+ sub intercept(&) {
587
+ my $code = shift;
588
+ my $ctx = context();
589
+
590
+ my $events = _intercept($code, deep => 0);
591
+
592
+ $ctx->release;
593
+
594
+ return $events;
595
+ }
596
+
597
+ sub intercept_deep(&) {
598
+ my $code = shift;
599
+ my $ctx = context();
600
+
601
+ my $events = _intercept($code, deep => 1);
602
+
603
+ $ctx->release;
604
+
605
+ return $events;
606
+ }
607
+
608
+ sub _intercept {
609
+ my $code = shift;
610
+ my %params = @_;
611
+ my $ctx = context();
612
+
613
+ my $ipc;
614
+ if (my $global_ipc = test2_ipc()) {
615
+ my $driver = blessed($global_ipc);
616
+ $ipc = $driver->new;
617
+ }
618
+
619
+ my $hub = Test2::Hub::Interceptor->new(
620
+ ipc => $ipc,
621
+ no_ending => 1,
622
+ );
623
+
624
+ my @events;
625
+ $hub->listen(sub { push @events => $_[1] }, inherit => $params{deep});
626
+
627
+ $ctx->stack->top; # Make sure there is a top hub before we begin.
628
+ $ctx->stack->push($hub);
629
+
630
+ my $trace = $ctx->trace;
631
+ my $state = {};
632
+ $hub->clean_inherited(trace => $trace, state => $state);
633
+
634
+ my ($ok, $err) = (1, undef);
635
+ T2_SUBTEST_WRAPPER: {
636
+ # Do not use 'try' cause it localizes __DIE__
637
+ $ok = eval { $code->(hub => $hub, context => $ctx->snapshot); 1 };
638
+ $err = $@;
639
+
640
+ # They might have done 'BEGIN { skip_all => "whatever" }'
641
+ if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && $err->isa('Test2::Hub::Interceptor::Terminator'))) {
642
+ $ok = 1;
643
+ $err = undef;
644
+ }
645
+ }
646
+
647
+ $hub->cull;
648
+ $ctx->stack->pop($hub);
649
+
650
+ $hub->restore_inherited(trace => $trace, state => $state);
651
+
652
+ $ctx->release;
653
+
654
+ die $err unless $ok;
655
+
656
+ $hub->finalize($trace, 1)
657
+ if $ok
658
+ && !$hub->no_ending
659
+ && !$hub->ended;
660
+
661
+ require Test2::API::InterceptResult;
662
+ return Test2::API::InterceptResult->new_from_ref(\@events);
663
+ }
664
+
665
+ sub run_subtest {
666
+ my ($name, $code, $params, @args) = @_;
667
+
668
+ $_->($name,$code,@args)
669
+ for Test2::API::test2_list_pre_subtest_callbacks();
670
+
671
+ $params = {buffered => $params} unless ref $params;
672
+ my $inherit_trace = delete $params->{inherit_trace};
673
+
674
+ my $ctx = context();
675
+
676
+ my $parent = $ctx->hub;
677
+
678
+ # If a parent is buffered then the child must be as well.
679
+ my $buffered = $params->{buffered} || $parent->{buffered};
680
+
681
+ $ctx->note($name) unless $buffered;
682
+
683
+ my $stack = $ctx->stack || $STACK;
684
+ my $hub = $stack->new_hub(
685
+ class => 'Test2::Hub::Subtest',
686
+ %$params,
687
+ buffered => $buffered,
688
+ );
689
+
690
+ my @events;
691
+ $hub->listen(sub { push @events => $_[1] });
692
+
693
+ if ($buffered) {
694
+ if (my $format = $hub->format) {
695
+ my $hide = $format->can('hide_buffered') ? $format->hide_buffered : 1;
696
+ $hub->format(undef) if $hide;
697
+ }
698
+ }
699
+
700
+ if ($inherit_trace) {
701
+ my $orig = $code;
702
+ $code = sub {
703
+ my $base_trace = $ctx->trace;
704
+ my $trace = $base_trace->snapshot(nested => 1 + $base_trace->nested);
705
+ my $st_ctx = Test2::API::Context->new(
706
+ trace => $trace,
707
+ hub => $hub,
708
+ );
709
+ $st_ctx->do_in_context($orig, @args);
710
+ };
711
+ }
712
+
713
+ my $start_stamp = time;
714
+
715
+ my ($ok, $err, $finished);
716
+ T2_SUBTEST_WRAPPER: {
717
+ # Do not use 'try' cause it localizes __DIE__
718
+ $ok = eval { $code->(@args); 1 };
719
+ $err = $@;
720
+
721
+ # They might have done 'BEGIN { skip_all => "whatever" }'
722
+ if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
723
+ $ok = undef;
724
+ $err = undef;
725
+ }
726
+ else {
727
+ $finished = 1;
728
+ }
729
+ }
730
+
731
+ my $stop_stamp = time;
732
+
733
+ if ($params->{no_fork}) {
734
+ if ($$ != $ctx->trace->pid) {
735
+ warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
736
+ exit 255;
737
+ }
738
+
739
+ if (get_tid() != $ctx->trace->tid) {
740
+ warn $ok ? "Started new thread inside subtest, but thread never finished!\n" : $err;
741
+ exit 255;
742
+ }
743
+ }
744
+ elsif (!$parent->is_local && !$parent->ipc) {
745
+ warn $ok ? "A new process or thread was started inside subtest, but IPC is not enabled!\n" : $err;
746
+ exit 255;
747
+ }
748
+
749
+ $stack->pop($hub);
750
+
751
+ my $trace = $ctx->trace;
752
+
753
+ my $bailed = $hub->bailed_out;
754
+
755
+ if (!$finished) {
756
+ if ($bailed && !$buffered) {
757
+ $ctx->bail($bailed->reason);
758
+ }
759
+ elsif ($bailed && $buffered) {
760
+ $ok = 1;
761
+ }
762
+ else {
763
+ my $code = $hub->exit_code;
764
+ $ok = !$code;
765
+ $err = "Subtest ended with exit code $code" if $code;
766
+ }
767
+ }
768
+
769
+ $hub->finalize($trace->snapshot(huuid => $hub->uuid, hid => $hub->hid, nested => $hub->nested, buffered => $buffered), 1)
770
+ if $ok
771
+ && !$hub->no_ending
772
+ && !$hub->ended;
773
+
774
+ my $pass = $ok && $hub->is_passing;
775
+ my $e = $ctx->build_event(
776
+ 'Subtest',
777
+ pass => $pass,
778
+ name => $name,
779
+ subtest_id => $hub->id,
780
+ subtest_uuid => $hub->uuid,
781
+ buffered => $buffered,
782
+ subevents => \@events,
783
+ start_stamp => $start_stamp,
784
+ stop_stamp => $stop_stamp,
785
+ );
786
+
787
+ my $plan_ok = $hub->check_plan;
788
+
789
+ $ctx->hub->send($e);
790
+
791
+ $ctx->failure_diag($e) unless $e->pass;
792
+
793
+ $ctx->diag("Caught exception in subtest: $err") unless $ok;
794
+
795
+ $ctx->diag("Bad subtest plan, expected " . $hub->plan . " but ran " . $hub->count)
796
+ if defined($plan_ok) && !$plan_ok;
797
+
798
+ $ctx->bail($bailed->reason) if $bailed && $buffered;
799
+
800
+ $ctx->release;
801
+ return $pass;
802
+ }
803
+
804
+ # There is a use-cycle between API and API/Context. Context needs to use some
805
+ # API functions as the package is compiling. Test2::API::context() needs
806
+ # Test2::API::Context to be loaded, but we cannot 'require' the module there as
807
+ # it causes a very noticeable performance impact with how often context() is
808
+ # called.
809
+ require Test2::API::Context;
810
+
811
+ # If the env var was set to load plugins, load them now, this is the earliest
812
+ # safe point to do so.
813
+ if (my $plugins = $ENV{TEST2_ENABLE_PLUGINS}) {
814
+ for my $p (split /\s*,\s*/, $plugins) {
815
+ $p = "Test2::Plugin::$p" unless $p =~ s/^\+//;
816
+ my $mod = "$p.pm";
817
+ $mod =~ s{::}{/}g;
818
+
819
+ if ($ENV{HARNESS_IS_VERBOSE} || !$ENV{HARNESS_ACTIVE}) {
820
+ # If the harness is verbose then just display the message for all to
821
+ # see. It is nice info and they already asked for noisy output.
822
+
823
+ test2_add_callback_post_load(sub {
824
+ test2_stack()->top; # Ensure we have at least 1 hub.
825
+ my ($hub) = test2_stack()->all;
826
+ $hub->send(
827
+ Test2::Event::Note->new(
828
+ trace => Test2::Util::Trace->new(frame => [__PACKAGE__, __FILE__, __LINE__, $p]),
829
+ message => "Loaded plugin '$p' as specified in the TEST2_ENABLE_PLUGINS env var.",
830
+ ),
831
+ );
832
+ });
833
+ }
834
+
835
+ eval {
836
+ package main;
837
+ require $mod;
838
+ $p->import;
839
+ 1
840
+ } or die "Could not load plugin '$p', which was specified in the TEST2_ENABLE_PLUGINS env var ($plugins): $@";
841
+ }
842
+ }
843
+
844
+ 1;
845
+
846
+ __END__
847
+
848
+ =pod
849
+
850
+ =encoding UTF-8
851
+
852
+ =head1 NAME
853
+
854
+ Test2::API - Primary interface for writing Test2 based testing tools.
855
+
856
+ =head1 ***INTERNALS NOTE***
857
+
858
+ B<The internals of this package are subject to change at any time!> The public
859
+ methods provided will not change in backwards-incompatible ways (once there is
860
+ a stable release), but the underlying implementation details might.
861
+ B<Do not break encapsulation here!>
862
+
863
+ Currently the implementation is to create a single instance of the
864
+ L<Test2::API::Instance> Object. All class methods defer to the single
865
+ instance. There is no public access to the singleton, and that is intentional.
866
+ The class methods provided by this package provide the only functionality
867
+ publicly exposed.
868
+
869
+ This is done primarily to avoid the problems Test::Builder had by exposing its
870
+ singleton. We do not want anyone to replace this singleton, rebless it, or
871
+ directly muck with its internals. If you need to do something and cannot
872
+ because of the restrictions placed here, then please report it as an issue. If
873
+ possible, we will create a way for you to implement your functionality without
874
+ exposing things that should not be exposed.
875
+
876
+ =head1 DESCRIPTION
877
+
878
+ This package exports all the functions necessary to write and/or verify testing
879
+ tools. Using these building blocks you can begin writing test tools very
880
+ quickly. You are also provided with tools that help you to test the tools you
881
+ write.
882
+
883
+ =head1 SYNOPSIS
884
+
885
+ =head2 WRITING A TOOL
886
+
887
+ The C<context()> method is your primary interface into the Test2 framework.
888
+
889
+ package My::Ok;
890
+ use Test2::API qw/context/;
891
+
892
+ our @EXPORT = qw/my_ok/;
893
+ use base 'Exporter';
894
+
895
+ # Just like ok() from Test::More
896
+ sub my_ok($;$) {
897
+ my ($bool, $name) = @_;
898
+ my $ctx = context(); # Get a context
899
+ $ctx->ok($bool, $name);
900
+ $ctx->release; # Release the context
901
+ return $bool;
902
+ }
903
+
904
+ See L<Test2::API::Context> for a list of methods available on the context object.
905
+
906
+ =head2 TESTING YOUR TOOLS
907
+
908
+ The C<intercept { ... }> tool lets you temporarily intercept all events
909
+ generated by the test system:
910
+
911
+ use Test2::API qw/intercept/;
912
+
913
+ use My::Ok qw/my_ok/;
914
+
915
+ my $events = intercept {
916
+ # These events are not displayed
917
+ my_ok(1, "pass");
918
+ my_ok(0, "fail");
919
+ };
920
+
921
+ As of version 1.302178 this now returns an arrayref that is also an instance of
922
+ L<Test2::API::InterceptResult>. See the L<Test2::API::InterceptResult>
923
+ documentation for details on how to best use it.
924
+
925
+ =head2 OTHER API FUNCTIONS
926
+
927
+ use Test2::API qw{
928
+ test2_init_done
929
+ test2_stack
930
+ test2_set_is_end
931
+ test2_get_is_end
932
+ test2_ipc
933
+ test2_formatter_set
934
+ test2_formatter
935
+ test2_is_testing_done
936
+ };
937
+
938
+ my $init = test2_init_done();
939
+ my $stack = test2_stack();
940
+ my $ipc = test2_ipc();
941
+
942
+ test2_formatter_set($FORMATTER)
943
+ my $formatter = test2_formatter();
944
+
945
+ ... And others ...
946
+
947
+ =head1 ENVIRONMENT VARIABLES
948
+
949
+ See L<Test2::Env> for a list of meaningul environment variables.
950
+
951
+ =head1 MAIN API EXPORTS
952
+
953
+ All exports are optional. You must specify subs to import.
954
+
955
+ use Test2::API qw/context intercept run_subtest/;
956
+
957
+ This is the list of exports that are most commonly needed. If you are simply
958
+ writing a tool, then this is probably all you need. If you need something and
959
+ you cannot find it here, then you can also look at L</OTHER API EXPORTS>.
960
+
961
+ These exports lack the 'test2_' prefix because of how important/common they
962
+ are. Exports in the L</OTHER API EXPORTS> section have the 'test2_' prefix to
963
+ ensure they stand out.
964
+
965
+ =head2 context(...)
966
+
967
+ Usage:
968
+
969
+ =over 4
970
+
971
+ =item $ctx = context()
972
+
973
+ =item $ctx = context(%params)
974
+
975
+ =back
976
+
977
+ The C<context()> function will always return the current context. If
978
+ there is already a context active, it will be returned. If there is not an
979
+ active context, one will be generated. When a context is generated it will
980
+ default to using the file and line number where the currently running sub was
981
+ called from.
982
+
983
+ Please see L<Test2::API::Context/"CRITICAL DETAILS"> for important rules about
984
+ what you can and cannot do with a context once it is obtained.
985
+
986
+ B<Note> This function will throw an exception if you ignore the context object
987
+ it returns.
988
+
989
+ B<Note> On perls 5.14+ a depth check is used to ensure there are no context
990
+ leaks. This cannot be safely done on older perls due to
991
+ L<https://rt.perl.org/Public/Bug/Display.html?id=127774>
992
+ You can forcefully enable it either by setting C<$ENV{T2_CHECK_DEPTH} = 1> or
993
+ C<$Test2::API::DO_DEPTH_CHECK = 1> B<BEFORE> loading L<Test2::API>.
994
+
995
+ =head3 OPTIONAL PARAMETERS
996
+
997
+ All parameters to C<context> are optional.
998
+
999
+ =over 4
1000
+
1001
+ =item level => $int
1002
+
1003
+ If you must obtain a context in a sub deeper than your entry point you can use
1004
+ this to tell it how many EXTRA stack frames to look back. If this option is not
1005
+ provided the default of C<0> is used.
1006
+
1007
+ sub third_party_tool {
1008
+ my $sub = shift;
1009
+ ... # Does not obtain a context
1010
+ $sub->();
1011
+ ...
1012
+ }
1013
+
1014
+ third_party_tool(sub {
1015
+ my $ctx = context(level => 1);
1016
+ ...
1017
+ $ctx->release;
1018
+ });
1019
+
1020
+ =item wrapped => $int
1021
+
1022
+ Use this if you need to write your own tool that wraps a call to C<context()>
1023
+ with the intent that it should return a context object.
1024
+
1025
+ sub my_context {
1026
+ my %params = ( wrapped => 0, @_ );
1027
+ $params{wrapped}++;
1028
+ my $ctx = context(%params);
1029
+ ...
1030
+ return $ctx;
1031
+ }
1032
+
1033
+ sub my_tool {
1034
+ my $ctx = my_context();
1035
+ ...
1036
+ $ctx->release;
1037
+ }
1038
+
1039
+ If you do not do this, then tools you call that also check for a context will
1040
+ notice that the context they grabbed was created at the same stack depth, which
1041
+ will trigger protective measures that warn you and destroy the existing
1042
+ context.
1043
+
1044
+ =item stack => $stack
1045
+
1046
+ Normally C<context()> looks at the global hub stack. If you are maintaining
1047
+ your own L<Test2::API::Stack> instance you may pass it in to be used
1048
+ instead of the global one.
1049
+
1050
+ =item hub => $hub
1051
+
1052
+ Use this parameter if you want to obtain the context for a specific hub instead
1053
+ of whatever one happens to be at the top of the stack.
1054
+
1055
+ =item on_init => sub { ... }
1056
+
1057
+ This lets you provide a callback sub that will be called B<ONLY> if your call
1058
+ to C<context()> generated a new context. The callback B<WILL NOT> be called if
1059
+ C<context()> is returning an existing context. The only argument passed into
1060
+ the callback will be the context object itself.
1061
+
1062
+ sub foo {
1063
+ my $ctx = context(on_init => sub { 'will run' });
1064
+
1065
+ my $inner = sub {
1066
+ # This callback is not run since we are getting the existing
1067
+ # context from our parent sub.
1068
+ my $ctx = context(on_init => sub { 'will NOT run' });
1069
+ $ctx->release;
1070
+ }
1071
+ $inner->();
1072
+
1073
+ $ctx->release;
1074
+ }
1075
+
1076
+ =item on_release => sub { ... }
1077
+
1078
+ This lets you provide a callback sub that will be called when the context
1079
+ instance is released. This callback will be added to the returned context even
1080
+ if an existing context is returned. If multiple calls to context add callbacks,
1081
+ then all will be called in reverse order when the context is finally released.
1082
+
1083
+ sub foo {
1084
+ my $ctx = context(on_release => sub { 'will run second' });
1085
+
1086
+ my $inner = sub {
1087
+ my $ctx = context(on_release => sub { 'will run first' });
1088
+
1089
+ # Neither callback runs on this release
1090
+ $ctx->release;
1091
+ }
1092
+ $inner->();
1093
+
1094
+ # Both callbacks run here.
1095
+ $ctx->release;
1096
+ }
1097
+
1098
+ =back
1099
+
1100
+ =head2 release($;$)
1101
+
1102
+ Usage:
1103
+
1104
+ =over 4
1105
+
1106
+ =item release $ctx;
1107
+
1108
+ =item release $ctx, ...;
1109
+
1110
+ =back
1111
+
1112
+ This is intended as a shortcut that lets you release your context and return a
1113
+ value in one statement. This function will get your context, and an optional
1114
+ return value. It will release your context, then return your value. Scalar
1115
+ context is always assumed.
1116
+
1117
+ sub tool {
1118
+ my $ctx = context();
1119
+ ...
1120
+
1121
+ return release $ctx, 1;
1122
+ }
1123
+
1124
+ This tool is most useful when you want to return the value you get from calling
1125
+ a function that needs to see the current context:
1126
+
1127
+ my $ctx = context();
1128
+ my $out = some_tool(...);
1129
+ $ctx->release;
1130
+ return $out;
1131
+
1132
+ We can combine the last 3 lines of the above like so:
1133
+
1134
+ my $ctx = context();
1135
+ release $ctx, some_tool(...);
1136
+
1137
+ =head2 context_do(&;@)
1138
+
1139
+ Usage:
1140
+
1141
+ sub my_tool {
1142
+ context_do {
1143
+ my $ctx = shift;
1144
+
1145
+ my (@args) = @_;
1146
+
1147
+ $ctx->ok(1, "pass");
1148
+
1149
+ ...
1150
+
1151
+ # No need to call $ctx->release, done for you on scope exit.
1152
+ } @_;
1153
+ }
1154
+
1155
+ Using this inside your test tool takes care of a lot of boilerplate for you. It
1156
+ will ensure a context is acquired. It will capture and rethrow any exception. It
1157
+ will ensure the context is released when you are done. It preserves the
1158
+ subroutine call context (list, scalar, void).
1159
+
1160
+ This is the safest way to write a test tool. The only two downsides to this are a
1161
+ slight performance decrease, and some extra indentation in your source. If the
1162
+ indentation is a problem for you then you can take a peek at the next section.
1163
+
1164
+ =head2 no_context(&;$)
1165
+
1166
+ Usage:
1167
+
1168
+ =over 4
1169
+
1170
+ =item no_context { ... };
1171
+
1172
+ =item no_context { ... } $hid;
1173
+
1174
+ sub my_tool(&) {
1175
+ my $code = shift;
1176
+ my $ctx = context();
1177
+ ...
1178
+
1179
+ no_context {
1180
+ # Things in here will not see our current context, they get a new
1181
+ # one.
1182
+
1183
+ $code->();
1184
+ };
1185
+
1186
+ ...
1187
+ $ctx->release;
1188
+ };
1189
+
1190
+ =back
1191
+
1192
+ This tool will hide a context for the provided block of code. This means any
1193
+ tools run inside the block will get a completely new context if they acquire
1194
+ one. The new context will be inherited by tools nested below the one that
1195
+ acquired it.
1196
+
1197
+ This will normally hide the current context for the top hub. If you need to
1198
+ hide the context for a different hub you can pass in the optional C<$hid>
1199
+ parameter.
1200
+
1201
+ =head2 intercept(&)
1202
+
1203
+ Usage:
1204
+
1205
+ my $events = intercept {
1206
+ ok(1, "pass");
1207
+ ok(0, "fail");
1208
+ ...
1209
+ };
1210
+
1211
+ This function takes a codeblock as its only argument, and it has a prototype.
1212
+ It will execute the codeblock, intercepting any generated events in the
1213
+ process. It will return an array reference with all the generated event
1214
+ objects. All events should be subclasses of L<Test2::Event>.
1215
+
1216
+ As of version 1.302178 the events array that is returned is blssed as an
1217
+ L<Test2::API::InterceptResult> instance. L<Test2::API::InterceptResult>
1218
+ Provides a helpful interface for filtering and/or inspecting the events list
1219
+ overall, or individual events within the list.
1220
+
1221
+ This is intended to help you test your test code. This is not intended for
1222
+ people simply writing tests.
1223
+
1224
+ =head2 run_subtest(...)
1225
+
1226
+ Usage:
1227
+
1228
+ run_subtest($NAME, \&CODE, $BUFFERED, @ARGS)
1229
+
1230
+ # or
1231
+
1232
+ run_subtest($NAME, \&CODE, \%PARAMS, @ARGS)
1233
+
1234
+ This will run the provided codeblock with the args in C<@args>. This codeblock
1235
+ will be run as a subtest. A subtest is an isolated test state that is condensed
1236
+ into a single L<Test2::Event::Subtest> event, which contains all events
1237
+ generated inside the subtest.
1238
+
1239
+ =head3 ARGUMENTS:
1240
+
1241
+ =over 4
1242
+
1243
+ =item $NAME
1244
+
1245
+ The name of the subtest.
1246
+
1247
+ =item \&CODE
1248
+
1249
+ The code to run inside the subtest.
1250
+
1251
+ =item $BUFFERED or \%PARAMS
1252
+
1253
+ If this is a simple scalar then it will be treated as a boolean for the
1254
+ 'buffered' setting. If this is a hash reference then it will be used as a
1255
+ parameters hash. The param hash will be used for hub construction (with the
1256
+ specified keys removed).
1257
+
1258
+ Keys that are removed and used by run_subtest:
1259
+
1260
+ =over 4
1261
+
1262
+ =item 'buffered' => $bool
1263
+
1264
+ Toggle buffered status.
1265
+
1266
+ =item 'inherit_trace' => $bool
1267
+
1268
+ Normally the subtest hub is pushed and the sub is allowed to generate its own
1269
+ root context for the hub. When this setting is turned on a root context will be
1270
+ created for the hub that shares the same trace as the current context.
1271
+
1272
+ Set this to true if your tool is producing subtests without user-specified
1273
+ subs.
1274
+
1275
+ =item 'no_fork' => $bool
1276
+
1277
+ Defaults to off. Normally forking inside a subtest will actually fork the
1278
+ subtest, resulting in 2 final subtest events. This parameter will turn off that
1279
+ behavior, only the original process/thread will return a final subtest event.
1280
+
1281
+ =back
1282
+
1283
+ =item @ARGS
1284
+
1285
+ Any extra arguments you want passed into the subtest code.
1286
+
1287
+ =back
1288
+
1289
+ =head3 BUFFERED VS UNBUFFERED (OR STREAMED)
1290
+
1291
+ Normally all events inside and outside a subtest are sent to the formatter
1292
+ immediately by the hub. Sometimes it is desirable to hold off sending events
1293
+ within a subtest until the subtest is complete. This usually depends on the
1294
+ formatter being used.
1295
+
1296
+ =over 4
1297
+
1298
+ =item Things not affected by this flag
1299
+
1300
+ In both cases events are generated and stored in an array. This array is
1301
+ eventually used to populate the C<subevents> attribute on the
1302
+ L<Test2::Event::Subtest> event that is generated at the end of the subtest.
1303
+ This flag has no effect on this part; it always happens.
1304
+
1305
+ At the end of the subtest, the final L<Test2::Event::Subtest> event is sent to
1306
+ the formatter.
1307
+
1308
+ =item Things that are affected by this flag
1309
+
1310
+ The C<buffered> attribute of the L<Test2::Event::Subtest> event will be set to
1311
+ the value of this flag. This means any formatter, listener, etc which looks at
1312
+ the event will know if it was buffered.
1313
+
1314
+ =item Things that are formatter dependent
1315
+
1316
+ Events within a buffered subtest may or may not be sent to the formatter as
1317
+ they happen. If a formatter fails to specify then the default is to B<NOT SEND>
1318
+ the events as they are generated, instead the formatter can pull them from the
1319
+ C<subevents> attribute.
1320
+
1321
+ A formatter can specify by implementing the C<hide_buffered()> method. If this
1322
+ method returns true then events generated inside a buffered subtest will not be
1323
+ sent independently of the final subtest event.
1324
+
1325
+ =back
1326
+
1327
+ An example of how this is used is the L<Test2::Formatter::TAP> formatter. For
1328
+ unbuffered subtests the events are rendered as they are generated. At the end
1329
+ of the subtest, the final subtest event is rendered, but the C<subevents>
1330
+ attribute is ignored. For buffered subtests the opposite occurs, the events are
1331
+ NOT rendered as they are generated, instead the C<subevents> attribute is used
1332
+ to render them all at once. This is useful when running subtests tests in
1333
+ parallel, since without it the output from subtests would be interleaved
1334
+ together.
1335
+
1336
+ =head1 OTHER API EXPORTS
1337
+
1338
+ Exports in this section are not commonly needed. These all have the 'test2_'
1339
+ prefix to help ensure they stand out. You should look at the L</MAIN API
1340
+ EXPORTS> section before looking here. This section is one where "Great power
1341
+ comes with great responsibility". It is possible to break things badly if you
1342
+ are not careful with these.
1343
+
1344
+ All exports are optional. You need to list which ones you want at import time:
1345
+
1346
+ use Test2::API qw/test2_init_done .../;
1347
+
1348
+ =head2 STATUS AND INITIALIZATION STATE
1349
+
1350
+ These provide access to internal state and object instances.
1351
+
1352
+ =over 4
1353
+
1354
+ =item $bool = test2_init_done()
1355
+
1356
+ This will return true if the stack and IPC instances have already been
1357
+ initialized. It will return false if they have not. Init happens as late as
1358
+ possible. It happens as soon as a tool requests the IPC instance, the
1359
+ formatter, or the stack.
1360
+
1361
+ =item $bool = test2_load_done()
1362
+
1363
+ This will simply return the boolean value of the loaded flag. If Test2 has
1364
+ finished loading this will be true, otherwise false. Loading is considered
1365
+ complete the first time a tool requests a context.
1366
+
1367
+ =item test2_set_is_end()
1368
+
1369
+ =item test2_set_is_end($bool)
1370
+
1371
+ This is used to toggle Test2's belief that the END phase has already started.
1372
+ With no arguments this will set it to true. With arguments it will set it to
1373
+ the first argument's value.
1374
+
1375
+ This is used to prevent the use of C<caller()> in END blocks which can cause
1376
+ segfaults. This is only necessary in some persistent environments that may have
1377
+ multiple END phases.
1378
+
1379
+ =item $bool = test2_get_is_end()
1380
+
1381
+ Check if Test2 believes it is the END phase.
1382
+
1383
+ =item $stack = test2_stack()
1384
+
1385
+ This will return the global L<Test2::API::Stack> instance. If this has not
1386
+ yet been initialized it will be initialized now.
1387
+
1388
+ =item $bool = test2_is_testing_done()
1389
+
1390
+ This will return true if testing is complete and no other events should be
1391
+ sent. This is useful in things like warning handlers where you might want to
1392
+ turn warnings into events, but need them to start acting like normal warnings
1393
+ when testing is done.
1394
+
1395
+ $SIG{__WARN__} = sub {
1396
+ my ($warning) = @_;
1397
+
1398
+ if (test2_is_testing_done()) {
1399
+ warn @_;
1400
+ }
1401
+ else {
1402
+ my $ctx = context();
1403
+ ...
1404
+ $ctx->release
1405
+ }
1406
+ }
1407
+
1408
+ =item test2_ipc_disable
1409
+
1410
+ Disable IPC.
1411
+
1412
+ =item $bool = test2_ipc_disabled
1413
+
1414
+ Check if IPC is disabled.
1415
+
1416
+ =item test2_ipc_wait_enable()
1417
+
1418
+ =item test2_ipc_wait_disable()
1419
+
1420
+ =item $bool = test2_ipc_wait_enabled()
1421
+
1422
+ These can be used to turn IPC waiting on and off, or check the current value of
1423
+ the flag.
1424
+
1425
+ Waiting is turned on by default. Waiting will cause the parent process/thread
1426
+ to wait until all child processes and threads are finished before exiting. You
1427
+ will almost never want to turn this off.
1428
+
1429
+ =item $bool = test2_no_wait()
1430
+
1431
+ =item test2_no_wait($bool)
1432
+
1433
+ B<DISCOURAGED>: This is a confusing interface, it is better to use
1434
+ C<test2_ipc_wait_enable()>, C<test2_ipc_wait_disable()> and
1435
+ C<test2_ipc_wait_enabled()>.
1436
+
1437
+ This can be used to get/set the no_wait status. Waiting is turned on by
1438
+ default. Waiting will cause the parent process/thread to wait until all child
1439
+ processes and threads are finished before exiting. You will almost never want
1440
+ to turn this off.
1441
+
1442
+ =item $fh = test2_stdout()
1443
+
1444
+ =item $fh = test2_stderr()
1445
+
1446
+ These functions return the filehandles that test output should be written to.
1447
+ They are primarily useful when writing a custom formatter and code that turns
1448
+ events into actual output (TAP, etc.). They will return a dupe of the original
1449
+ filehandles that formatted output can be sent to regardless of whatever state
1450
+ the currently running test may have left STDOUT and STDERR in.
1451
+
1452
+ =item test2_reset_io()
1453
+
1454
+ Re-dupe the internal filehandles returned by C<test2_stdout()> and
1455
+ C<test2_stderr()> from the current STDOUT and STDERR. You shouldn't need to do
1456
+ this except in very peculiar situations (for example, you're testing a new
1457
+ formatter and you need control over where the formatter is sending its output.)
1458
+
1459
+ =back
1460
+
1461
+ =head2 BEHAVIOR HOOKS
1462
+
1463
+ These are hooks that allow you to add custom behavior to actions taken by Test2
1464
+ and tools built on top of it.
1465
+
1466
+ =over 4
1467
+
1468
+ =item test2_add_callback_exit(sub { ... })
1469
+
1470
+ This can be used to add a callback that is called after all testing is done. This
1471
+ is too late to add additional results, the main use of this callback is to set the
1472
+ exit code.
1473
+
1474
+ test2_add_callback_exit(
1475
+ sub {
1476
+ my ($context, $exit, \$new_exit) = @_;
1477
+ ...
1478
+ }
1479
+ );
1480
+
1481
+ The C<$context> passed in will be an instance of L<Test2::API::Context>. The
1482
+ C<$exit> argument will be the original exit code before anything modified it.
1483
+ C<$$new_exit> is a reference to the new exit code. You may modify this to
1484
+ change the exit code. Please note that C<$$new_exit> may already be different
1485
+ from C<$exit>
1486
+
1487
+ =item test2_add_callback_post_load(sub { ... })
1488
+
1489
+ Add a callback that will be called when Test2 is finished loading. This
1490
+ means the callback will be run once, the first time a context is obtained.
1491
+ If Test2 has already finished loading then the callback will be run immediately.
1492
+
1493
+ =item test2_add_callback_testing_done(sub { ... })
1494
+
1495
+ This adds your coderef as a follow-up to the root hub after Test2 is finished loading.
1496
+
1497
+ This is essentially a helper to do the following:
1498
+
1499
+ test2_add_callback_post_load(sub {
1500
+ my $stack = test2_stack();
1501
+ $stack->top; # Ensure we have a hub
1502
+ my ($hub) = Test2::API::test2_stack->all;
1503
+
1504
+ $hub->set_active(1);
1505
+
1506
+ $hub->follow_up(sub { ... }); # <-- Your coderef here
1507
+ });
1508
+
1509
+ =item test2_add_callback_context_acquire(sub { ... })
1510
+
1511
+ Add a callback that will be called every time someone tries to acquire a
1512
+ context. This will be called on EVERY call to C<context()>. It gets a single
1513
+ argument, a reference to the hash of parameters being used the construct the
1514
+ context. This is your chance to change the parameters by directly altering the
1515
+ hash.
1516
+
1517
+ test2_add_callback_context_acquire(sub {
1518
+ my $params = shift;
1519
+ $params->{level}++;
1520
+ });
1521
+
1522
+ This is a very scary API function. Please do not use this unless you need to.
1523
+ This is here for L<Test::Builder> and backwards compatibility. This has you
1524
+ directly manipulate the hash instead of returning a new one for performance
1525
+ reasons.
1526
+
1527
+ =item test2_add_callback_context_init(sub { ... })
1528
+
1529
+ Add a callback that will be called every time a new context is created. The
1530
+ callback will receive the newly created context as its only argument.
1531
+
1532
+ =item test2_add_callback_context_release(sub { ... })
1533
+
1534
+ Add a callback that will be called every time a context is released. The
1535
+ callback will receive the released context as its only argument.
1536
+
1537
+ =item test2_add_callback_pre_subtest(sub { ... })
1538
+
1539
+ Add a callback that will be called every time a subtest is going to be
1540
+ run. The callback will receive the subtest name, coderef, and any
1541
+ arguments.
1542
+
1543
+ =item @list = test2_list_context_acquire_callbacks()
1544
+
1545
+ Return all the context acquire callback references.
1546
+
1547
+ =item @list = test2_list_context_init_callbacks()
1548
+
1549
+ Returns all the context init callback references.
1550
+
1551
+ =item @list = test2_list_context_release_callbacks()
1552
+
1553
+ Returns all the context release callback references.
1554
+
1555
+ =item @list = test2_list_exit_callbacks()
1556
+
1557
+ Returns all the exit callback references.
1558
+
1559
+ =item @list = test2_list_post_load_callbacks()
1560
+
1561
+ Returns all the post load callback references.
1562
+
1563
+ =item @list = test2_list_pre_subtest_callbacks()
1564
+
1565
+ Returns all the pre-subtest callback references.
1566
+
1567
+ =item test2_add_uuid_via(sub { ... })
1568
+
1569
+ =item $sub = test2_add_uuid_via()
1570
+
1571
+ This allows you to provide a UUID generator. If provided UUIDs will be attached
1572
+ to all events, hubs, and contexts. This is useful for storing, tracking, and
1573
+ linking these objects.
1574
+
1575
+ The sub you provide should always return a unique identifier. Most things will
1576
+ expect a proper UUID string, however nothing in Test2::API enforces this.
1577
+
1578
+ The sub will receive exactly 1 argument, the type of thing being tagged
1579
+ 'context', 'hub', or 'event'. In the future additional things may be tagged, in
1580
+ which case new strings will be passed in. These are purely informative, you can
1581
+ (and usually should) ignore them.
1582
+
1583
+ =item test2_add_pending_diag($diag)
1584
+
1585
+ =item test2_add_pending_diag($diag1, $diag2)
1586
+
1587
+ Add a diagnostics message that will be issued the next time a context in which
1588
+ a failure occured is released.
1589
+
1590
+ This can also be thought of like this: "If the next bit causes a failed
1591
+ assertion, add this diagnostics message".
1592
+
1593
+ =item @diags = test2_get_pending_diags()
1594
+
1595
+ Get all the current pending diagnostics messages.
1596
+
1597
+ =item @diags = test2_clear_pending_diags()
1598
+
1599
+ Clear any pending diagnostics, returning them.
1600
+
1601
+ =back
1602
+
1603
+ =head2 IPC AND CONCURRENCY
1604
+
1605
+ These let you access, or specify, the IPC system internals.
1606
+
1607
+ =over 4
1608
+
1609
+ =item $bool = test2_has_ipc()
1610
+
1611
+ Check if IPC is enabled.
1612
+
1613
+ =item $ipc = test2_ipc()
1614
+
1615
+ This will return the global L<Test2::IPC::Driver> instance. If this has not yet
1616
+ been initialized it will be initialized now.
1617
+
1618
+ =item test2_ipc_add_driver($DRIVER)
1619
+
1620
+ Add an IPC driver to the list. This will add the driver to the start of the
1621
+ list.
1622
+
1623
+ =item @drivers = test2_ipc_drivers()
1624
+
1625
+ Get the list of IPC drivers.
1626
+
1627
+ =item $bool = test2_ipc_polling()
1628
+
1629
+ Check if polling is enabled.
1630
+
1631
+ =item test2_ipc_enable_polling()
1632
+
1633
+ Turn on polling. This will cull events from other processes and threads every
1634
+ time a context is created.
1635
+
1636
+ =item test2_ipc_disable_polling()
1637
+
1638
+ Turn off IPC polling.
1639
+
1640
+ =item test2_ipc_enable_shm()
1641
+
1642
+ Legacy, this is currently a no-op that returns 0;
1643
+
1644
+ =item test2_ipc_set_pending($uniq_val)
1645
+
1646
+ Tell other processes and events that an event is pending. C<$uniq_val> should
1647
+ be a unique value no other thread/process will generate.
1648
+
1649
+ B<Note:> After calling this C<test2_ipc_get_pending()> will return 1. This is
1650
+ intentional, and not avoidable.
1651
+
1652
+ =item $pending = test2_ipc_get_pending()
1653
+
1654
+ This returns -1 if there is no way to check (assume yes)
1655
+
1656
+ This returns 0 if there are (most likely) no pending events.
1657
+
1658
+ This returns 1 if there are (likely) pending events. Upon return it will reset,
1659
+ nothing else will be able to see that there were pending events.
1660
+
1661
+ =item $timeout = test2_ipc_get_timeout()
1662
+
1663
+ =item test2_ipc_set_timeout($timeout)
1664
+
1665
+ Get/Set the timeout value for the IPC system. This timeout is how long the IPC
1666
+ system will wait for child processes and threads to finish before aborting.
1667
+
1668
+ The default value is C<30> seconds.
1669
+
1670
+ =back
1671
+
1672
+ =head2 MANAGING FORMATTERS
1673
+
1674
+ These let you access, or specify, the formatters that can/should be used.
1675
+
1676
+ =over 4
1677
+
1678
+ =item $formatter = test2_formatter
1679
+
1680
+ This will return the global formatter class. This is not an instance. By
1681
+ default the formatter is set to L<Test2::Formatter::TAP>.
1682
+
1683
+ You can override this default using the C<T2_FORMATTER> environment variable.
1684
+
1685
+ Normally 'Test2::Formatter::' is prefixed to the value in the
1686
+ environment variable:
1687
+
1688
+ $ T2_FORMATTER='TAP' perl test.t # Use the Test2::Formatter::TAP formatter
1689
+ $ T2_FORMATTER='Foo' perl test.t # Use the Test2::Formatter::Foo formatter
1690
+
1691
+ If you want to specify a full module name you use the '+' prefix:
1692
+
1693
+ $ T2_FORMATTER='+Foo::Bar' perl test.t # Use the Foo::Bar formatter
1694
+
1695
+ =item test2_formatter_set($class_or_instance)
1696
+
1697
+ Set the global formatter class. This can only be set once. B<Note:> This will
1698
+ override anything specified in the 'T2_FORMATTER' environment variable.
1699
+
1700
+ =item @formatters = test2_formatters()
1701
+
1702
+ Get a list of all loaded formatters.
1703
+
1704
+ =item test2_formatter_add($class_or_instance)
1705
+
1706
+ Add a formatter to the list. Last formatter added is used at initialization. If
1707
+ this is called after initialization a warning will be issued.
1708
+
1709
+ =back
1710
+
1711
+ =head2 TIME STAMPS
1712
+
1713
+ You can enable or disable timestamps in trace facets. They are disabled by
1714
+ default for compatibility and performance reasons.
1715
+
1716
+ =over 4
1717
+
1718
+ =item test2_enable_trace_stamps()
1719
+
1720
+ Enable stamps in traces.
1721
+
1722
+ =item test2_disable_trace_stamps()
1723
+
1724
+ Disable stamps in traces.
1725
+
1726
+ =item $bool = test2_trace_stamps_enabled()
1727
+
1728
+ Check status of trace stamps.
1729
+
1730
+ =back
1731
+
1732
+ =head1 OTHER EXAMPLES
1733
+
1734
+ See the C</Examples/> directory included in this distribution.
1735
+
1736
+ =head1 SEE ALSO
1737
+
1738
+ L<Test2::API::Context> - Detailed documentation of the context object.
1739
+
1740
+ L<Test2::IPC> - The IPC system used for threading/fork support.
1741
+
1742
+ L<Test2::Formatter> - Formatters such as TAP live here.
1743
+
1744
+ L<Test2::Event> - Events live in this namespace.
1745
+
1746
+ L<Test2::Hub> - All events eventually funnel through a hub. Custom hubs are how
1747
+ C<intercept()> and C<run_subtest()> are implemented.
1748
+
1749
+ =head1 MAGIC
1750
+
1751
+ This package has an END block. This END block is responsible for setting the
1752
+ exit code based on the test results. This end block also calls the callbacks that
1753
+ can be added to this package.
1754
+
1755
+ =head1 SOURCE
1756
+
1757
+ The source code repository for Test2 can be found at
1758
+ L<https://github.com/Test-More/test-more/>.
1759
+
1760
+ =head1 MAINTAINERS
1761
+
1762
+ =over 4
1763
+
1764
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
1765
+
1766
+ =back
1767
+
1768
+ =head1 AUTHORS
1769
+
1770
+ =over 4
1771
+
1772
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
1773
+
1774
+ =back
1775
+
1776
+ =head1 COPYRIGHT
1777
+
1778
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
1779
+
1780
+ This program is free software; you can redistribute it and/or
1781
+ modify it under the same terms as Perl itself.
1782
+
1783
+ See L<https://dev.perl.org/licenses/>
1784
+
1785
+ =cut
git/usr/share/perl5/core_perl/Test2/AsyncSubtest.pm ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::AsyncSubtest;
2
+ use strict;
3
+ use warnings;
4
+
5
+ use Test2::IPC;
6
+
7
+ our $VERSION = '1.302210';
8
+
9
+ our @CARP_NOT = qw/Test2::Util::HashBase/;
10
+
11
+ use Carp qw/croak cluck confess/;
12
+ use Test2::Util qw/get_tid CAN_THREAD CAN_FORK/;
13
+ use Scalar::Util qw/blessed weaken/;
14
+ use List::Util qw/first/;
15
+
16
+ use Test2::API();
17
+ use Test2::API::Context();
18
+ use Test2::Util::Trace();
19
+ use Test2::Util::Guard();
20
+ use Time::HiRes();
21
+
22
+ use Test2::AsyncSubtest::Hub();
23
+ use Test2::AsyncSubtest::Event::Attach();
24
+ use Test2::AsyncSubtest::Event::Detach();
25
+
26
+ use Test2::Util::HashBase qw{
27
+ name hub
28
+ trace frame send_to
29
+ events
30
+ finished
31
+ active
32
+ stack
33
+ id cid uuid
34
+ children
35
+ _in_use
36
+ _attached pid tid
37
+ start_stamp stop_stamp
38
+ };
39
+
40
+ sub CAN_REALLY_THREAD {
41
+ return 0 unless CAN_THREAD;
42
+ return 0 unless eval { require threads; threads->VERSION('1.34'); 1 };
43
+ return 1;
44
+ }
45
+
46
+
47
+ my $UUID_VIA = Test2::API::_add_uuid_via_ref();
48
+ my $CID = 1;
49
+ my @STACK;
50
+
51
+ sub TOP { @STACK ? $STACK[-1] : undef }
52
+
53
+ sub init {
54
+ my $self = shift;
55
+
56
+ croak "'name' is a required attribute"
57
+ unless $self->{+NAME};
58
+
59
+ my $to = $self->{+SEND_TO} ||= Test2::API::test2_stack()->top;
60
+
61
+ $self->{+STACK} = [@STACK];
62
+ $_->{+_IN_USE}++ for reverse @STACK;
63
+
64
+ $self->{+TID} = get_tid;
65
+ $self->{+PID} = $$;
66
+ $self->{+CID} = 'AsyncSubtest-' . $CID++;
67
+ $self->{+ID} = 1;
68
+ $self->{+FINISHED} = 0;
69
+ $self->{+ACTIVE} = 0;
70
+ $self->{+_IN_USE} = 0;
71
+ $self->{+CHILDREN} = [];
72
+ $self->{+UUID} = ${$UUID_VIA}->() if defined $$UUID_VIA;
73
+
74
+ unless($self->{+HUB}) {
75
+ my $ipc = Test2::API::test2_ipc();
76
+ my $formatter = Test2::API::test2_stack->top->format;
77
+ my $args = delete $self->{hub_init_args} || {};
78
+ my $hub = Test2::AsyncSubtest::Hub->new(
79
+ %$args,
80
+ ipc => $ipc,
81
+ nested => $to->nested + 1,
82
+ buffered => 1,
83
+ formatter => $formatter,
84
+ );
85
+ weaken($hub->{ast} = $self);
86
+ $self->{+HUB} = $hub;
87
+ }
88
+
89
+ $self->{+TRACE} ||= Test2::Util::Trace->new(
90
+ frame => $self->{+FRAME} || [caller(1)],
91
+ buffered => $to->buffered,
92
+ nested => $to->nested,
93
+ cid => $self->{+CID},
94
+ uuid => $self->{+UUID},
95
+ hid => $to->hid,
96
+ huuid => $to->uuid,
97
+ );
98
+
99
+ my $hub = $self->{+HUB};
100
+ $hub->set_ast_ids({}) unless $hub->ast_ids;
101
+ $hub->listen($self->_listener);
102
+ }
103
+
104
+ sub _listener {
105
+ my $self = shift;
106
+
107
+ my $events = $self->{+EVENTS} ||= [];
108
+
109
+ sub { push @$events => $_[1] };
110
+ }
111
+
112
+ sub context {
113
+ my $self = shift;
114
+
115
+ my $send_to = $self->{+SEND_TO};
116
+
117
+ confess "Attempt to close AsyncSubtest when original parent hub (a non async-subtest?) has ended"
118
+ if $send_to->ended;
119
+
120
+ return Test2::API::Context->new(
121
+ trace => $self->{+TRACE},
122
+ hub => $send_to,
123
+ );
124
+ }
125
+
126
+ sub _gen_event {
127
+ my $self = shift;
128
+ my ($type, $id, $hub) = @_;
129
+
130
+ my $class = "Test2::AsyncSubtest::Event::$type";
131
+
132
+ return $class->new(
133
+ id => $id,
134
+ trace => Test2::Util::Trace->new(
135
+ frame => [caller(1)],
136
+ buffered => $hub->buffered,
137
+ nested => $hub->nested,
138
+ cid => $self->{+CID},
139
+ uuid => $self->{+UUID},
140
+ hid => $hub->hid,
141
+ huuid => $hub->uuid,
142
+ ),
143
+ );
144
+ }
145
+
146
+ sub cleave {
147
+ my $self = shift;
148
+ my $id = $self->{+ID}++;
149
+ $self->{+HUB}->ast_ids->{$id} = 0;
150
+ return $id;
151
+ }
152
+
153
+ sub attach {
154
+ my $self = shift;
155
+ my ($id) = @_;
156
+
157
+ croak "An ID is required" unless $id;
158
+
159
+ croak "ID $id is not valid"
160
+ unless defined $self->{+HUB}->ast_ids->{$id};
161
+
162
+ croak "ID $id is already attached"
163
+ if $self->{+HUB}->ast_ids->{$id};
164
+
165
+ croak "You must attach INSIDE the child process/thread"
166
+ if $self->{+HUB}->is_local;
167
+
168
+ $self->{+_ATTACHED} = [ $$, get_tid, $id ];
169
+ $self->{+HUB}->send($self->_gen_event('Attach', $id, $self->{+HUB}));
170
+ }
171
+
172
+ sub detach {
173
+ my $self = shift;
174
+
175
+ if ($self->{+PID} == $$ && $self->{+TID} == get_tid) {
176
+ cluck "You must detach INSIDE the child process/thread ($$, " . get_tid . " instead of $self->{+PID}, $self->{+TID})";
177
+ return;
178
+ }
179
+
180
+ my $att = $self->{+_ATTACHED}
181
+ or croak "Not attached";
182
+
183
+ croak "Attempt to detach from wrong child"
184
+ unless $att->[0] == $$ && $att->[1] == get_tid;
185
+
186
+ my $id = $att->[2];
187
+
188
+ $self->{+HUB}->send($self->_gen_event('Detach', $id, $self->{+HUB}));
189
+
190
+ delete $self->{+_ATTACHED};
191
+ }
192
+
193
+ sub ready { return !shift->pending }
194
+ sub pending {
195
+ my $self = shift;
196
+ my $hub = $self->{+HUB};
197
+ return -1 unless $hub->is_local;
198
+
199
+ $hub->cull;
200
+
201
+ return $self->{+_IN_USE} + keys %{$self->{+HUB}->ast_ids};
202
+ }
203
+
204
+ sub run {
205
+ my $self = shift;
206
+ my ($code, @args) = @_;
207
+
208
+ croak "AsyncSubtest->run() takes a codeblock as the first argument"
209
+ unless $code && ref($code) eq 'CODE';
210
+
211
+ $self->start;
212
+
213
+ my ($ok, $err, $finished);
214
+ T2_SUBTEST_WRAPPER: {
215
+ $ok = eval { $code->(@args); 1 };
216
+ $err = $@;
217
+
218
+ # They might have done 'BEGIN { skip_all => "whatever" }'
219
+ if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/) {
220
+ $ok = undef;
221
+ $err = undef;
222
+ }
223
+ else {
224
+ $finished = 1;
225
+ }
226
+ }
227
+
228
+ $self->stop;
229
+
230
+ my $hub = $self->{+HUB};
231
+
232
+ if (!$finished) {
233
+ if(my $bailed = $hub->bailed_out) {
234
+ my $ctx = $self->context;
235
+ $ctx->bail($bailed->reason);
236
+ return;
237
+ }
238
+ my $code = $hub->exit_code;
239
+ $ok = !$code;
240
+ $err = "Subtest ended with exit code $code" if $code;
241
+ }
242
+
243
+ unless ($ok) {
244
+ my $e = Test2::Event::Exception->new(
245
+ error => $err,
246
+ trace => Test2::Util::Trace->new(
247
+ frame => [caller(0)],
248
+ buffered => $hub->buffered,
249
+ nested => $hub->nested,
250
+ cid => $self->{+CID},
251
+ uuid => $self->{+UUID},
252
+ hid => $hub->hid,
253
+ huuid => $hub->uuid,
254
+ ),
255
+ );
256
+ $hub->send($e);
257
+ }
258
+
259
+ return $hub->is_passing;
260
+ }
261
+
262
+ sub start {
263
+ my $self = shift;
264
+
265
+ croak "Subtest is already complete"
266
+ if $self->{+FINISHED};
267
+
268
+ $self->{+START_STAMP} = Time::HiRes::time() unless defined $self->{+START_STAMP};
269
+
270
+ $self->{+ACTIVE}++;
271
+
272
+ push @STACK => $self;
273
+ my $hub = $self->{+HUB};
274
+ my $stack = Test2::API::test2_stack();
275
+ $stack->push($hub);
276
+
277
+ return $hub->is_passing;
278
+ }
279
+
280
+ sub stop {
281
+ my $self = shift;
282
+
283
+ croak "Subtest is not active"
284
+ unless $self->{+ACTIVE}--;
285
+
286
+ croak "AsyncSubtest stack mismatch"
287
+ unless @STACK && $self == $STACK[-1];
288
+
289
+ $self->{+STOP_STAMP} = Time::HiRes::time();
290
+
291
+ pop @STACK;
292
+
293
+ my $hub = $self->{+HUB};
294
+ my $stack = Test2::API::test2_stack();
295
+ $stack->pop($hub);
296
+ return $hub->is_passing;
297
+ }
298
+
299
+ sub finish {
300
+ my $self = shift;
301
+ my %params = @_;
302
+
303
+ my $hub = $self->hub;
304
+
305
+ croak "Subtest is already finished"
306
+ if $self->{+FINISHED}++;
307
+
308
+ croak "Subtest can only be finished in the process/thread that created it"
309
+ unless $hub->is_local;
310
+
311
+ croak "Subtest is still active"
312
+ if $self->{+ACTIVE};
313
+
314
+ $self->wait;
315
+ $self->{+STOP_STAMP} = Time::HiRes::time() unless defined $self->{+STOP_STAMP};
316
+ my $stop_stamp = $self->{+STOP_STAMP};
317
+
318
+ my $todo = $params{todo};
319
+ my $skip = $params{skip};
320
+ my $empty = !@{$self->{+EVENTS}};
321
+ my $no_asserts = !$hub->count;
322
+ my $collapse = $params{collapse};
323
+ my $no_plan = $params{no_plan} || ($collapse && $no_asserts) || $skip;
324
+
325
+ my $trace = Test2::Util::Trace->new(
326
+ frame => $self->{+TRACE}->{frame},
327
+ buffered => $hub->buffered,
328
+ nested => $hub->nested,
329
+ cid => $self->{+CID},
330
+ uuid => $self->{+UUID},
331
+ hid => $hub->hid,
332
+ huuid => $hub->uuid,
333
+ );
334
+
335
+ $hub->finalize($trace, !$no_plan)
336
+ unless $hub->no_ending || $hub->ended;
337
+
338
+ if ($hub->ipc) {
339
+ $hub->ipc->drop_hub($hub->hid);
340
+ $hub->set_ipc(undef);
341
+ }
342
+
343
+ return $hub->is_passing if $params{silent};
344
+
345
+ my $ctx = $self->context;
346
+
347
+ my $pass = 1;
348
+ if ($skip) {
349
+ $ctx->skip($self->{+NAME}, $skip);
350
+ }
351
+ else {
352
+ if ($collapse && $empty) {
353
+ $ctx->ok($hub->is_passing, $self->{+NAME});
354
+ return $hub->is_passing;
355
+ }
356
+
357
+ if ($collapse && $no_asserts) {
358
+ push @{$self->{+EVENTS}} => Test2::Event::Plan->new(trace => $trace, max => 0, directive => 'SKIP', reason => "No assertions");
359
+ }
360
+
361
+ my $e = $ctx->build_event(
362
+ 'Subtest',
363
+ pass => $hub->is_passing,
364
+ subtest_id => $hub->id,
365
+ subtest_uuid => $hub->uuid,
366
+ name => $self->{+NAME},
367
+ buffered => 1,
368
+ subevents => $self->{+EVENTS},
369
+ start_stamp => $self->{+START_STAMP},
370
+ stop_stamp => $self->{+STOP_STAMP},
371
+ $todo ? (
372
+ todo => $todo,
373
+ effective_pass => 1,
374
+ ) : (),
375
+ );
376
+
377
+ $ctx->hub->send($e);
378
+
379
+ unless ($e->effective_pass) {
380
+ $ctx->failure_diag($e);
381
+
382
+ $ctx->diag("Bad subtest plan, expected " . $hub->plan . " but ran " . $hub->count)
383
+ if $hub->plan && !$hub->check_plan && !grep {$_->causes_fail} @{$self->{+EVENTS}};
384
+ }
385
+
386
+ $pass = $e->pass;
387
+ }
388
+
389
+ $_->{+_IN_USE}-- for reverse @{$self->{+STACK}};
390
+
391
+ return $pass;
392
+ }
393
+
394
+ sub wait {
395
+ my $self = shift;
396
+
397
+ my $hub = $self->{+HUB};
398
+ my $children = $self->{+CHILDREN};
399
+
400
+ while (@$children) {
401
+ $hub->cull;
402
+ if (my $child = pop @$children) {
403
+ if (blessed($child)) {
404
+ $child->join;
405
+ }
406
+ else {
407
+ waitpid($child, 0);
408
+ }
409
+ }
410
+ else {
411
+ Time::HiRes::sleep('0.01');
412
+ }
413
+ }
414
+
415
+ $hub->cull;
416
+
417
+ cluck "Subtest '$self->{+NAME}': All children have completed, but we still appear to be pending"
418
+ if $hub->is_local && keys %{$self->{+HUB}->ast_ids};
419
+ }
420
+
421
+ sub fork {
422
+ croak "Forking is not supported" unless CAN_FORK;
423
+ my $self = shift;
424
+ my $id = $self->cleave;
425
+ my $pid = CORE::fork();
426
+
427
+ unless (defined $pid) {
428
+ delete $self->{+HUB}->ast_ids->{$id};
429
+ croak "Failed to fork";
430
+ }
431
+
432
+ if($pid) {
433
+ push @{$self->{+CHILDREN}} => $pid;
434
+ return $pid;
435
+ }
436
+
437
+ $self->attach($id);
438
+
439
+ return $self->_guard;
440
+ }
441
+
442
+ sub run_fork {
443
+ my $self = shift;
444
+ my ($code, @args) = @_;
445
+
446
+ my $f = $self->fork;
447
+ return $f unless blessed($f);
448
+
449
+ $self->run($code, @args);
450
+
451
+ $self->detach();
452
+ $f->dismiss();
453
+ exit 0;
454
+ }
455
+
456
+ sub run_thread {
457
+ croak "Threading is not supported"
458
+ unless CAN_REALLY_THREAD;
459
+
460
+ my $self = shift;
461
+ my ($code, @args) = @_;
462
+
463
+ my $id = $self->cleave;
464
+ my $thr = threads->create(sub {
465
+ $self->attach($id);
466
+
467
+ $self->run($code, @args);
468
+
469
+ $self->detach(get_tid);
470
+ return 0;
471
+ });
472
+
473
+ push @{$self->{+CHILDREN}} => $thr;
474
+
475
+ return $thr;
476
+ }
477
+
478
+ sub _guard {
479
+ my $self = shift;
480
+
481
+ my ($pid, $tid) = ($$, get_tid);
482
+
483
+ return Test2::Util::Guard->new(sub {
484
+ return unless $$ == $pid && get_tid == $tid;
485
+
486
+ my $error = "Scope Leak";
487
+ if (my $ex = $@) {
488
+ chomp($ex);
489
+ $error .= " ($ex)";
490
+ }
491
+
492
+ cluck $error;
493
+
494
+ my $e = $self->context->build_event(
495
+ 'Exception',
496
+ error => "$error\n",
497
+ );
498
+ $self->{+HUB}->send($e);
499
+ $self->detach();
500
+ exit 255;
501
+ });
502
+ }
503
+
504
+ sub DESTROY {
505
+ my $self = shift;
506
+ return unless $self->{+NAME};
507
+
508
+ if (my $att = $self->{+_ATTACHED}) {
509
+ return unless $self->{+HUB};
510
+ eval { $self->detach() };
511
+ }
512
+
513
+ return if $self->{+FINISHED};
514
+ return unless $self->{+PID} == $$;
515
+ return unless $self->{+TID} == get_tid;
516
+
517
+ local $@;
518
+ eval { $_->{+_IN_USE}-- for reverse @{$self->{+STACK}} };
519
+
520
+ warn "Subtest $self->{+NAME} did not finish!";
521
+ exit 255;
522
+ }
523
+
524
+ 1;
525
+
526
+ __END__
527
+
528
+ =pod
529
+
530
+ =encoding UTF-8
531
+
532
+ =head1 NAME
533
+
534
+ Test2::AsyncSubtest - Object representing an async subtest.
535
+
536
+ =head1 DESCRIPTION
537
+
538
+ Regular subtests have a limited scope, they start, events are generated, then
539
+ they close and send an L<Test2::Event::Subtest> event. This is a problem if you
540
+ want the subtest to keep receiving events while other events are also being
541
+ generated. This class implements subtests that stay open until you decide to
542
+ close them.
543
+
544
+ This is mainly useful for tools that start a subtest in one process and then
545
+ spawn children. In many cases it is nice to let the parent process continue
546
+ instead of waiting on the children.
547
+
548
+ =head1 SYNOPSIS
549
+
550
+ use Test2::AsyncSubtest;
551
+
552
+ my $ast = Test2::AsyncSubtest->new(name => foo);
553
+
554
+ $ast->run(sub {
555
+ ok(1, "Event in parent" );
556
+ });
557
+
558
+ ok(1, "Event outside of subtest");
559
+
560
+ $ast->run_fork(sub {
561
+ ok(1, "Event in child process");
562
+ });
563
+
564
+ ...
565
+
566
+ $ast->finish;
567
+
568
+ done_testing;
569
+
570
+ =head1 CONSTRUCTION
571
+
572
+ my $ast = Test2::AsyncSubtest->new( ... );
573
+
574
+ =over 4
575
+
576
+ =item name => $name (required)
577
+
578
+ Name of the subtest. This construction argument is required.
579
+
580
+ =item send_to => $hub (optional)
581
+
582
+ Hub to which the final subtest event should be sent. This must be an instance
583
+ of L<Test2::Hub> or a subclass. If none is specified then the current top hub
584
+ will be used.
585
+
586
+ =item trace => $trace (optional)
587
+
588
+ File/Line to which errors should be attributed. This must be an instance of
589
+ L<Test2::Util::Trace>. If none is specified then the file/line where the
590
+ constructor was called will be used.
591
+
592
+ =item hub => $hub (optional)
593
+
594
+ Use this to specify a hub the subtest should use. By default a new hub is
595
+ generated. This must be an instance of L<Test2::AsyncSubtest::Hub>.
596
+
597
+ =back
598
+
599
+ =head1 METHODS
600
+
601
+ =head2 SIMPLE ACCESSORS
602
+
603
+ =over 4
604
+
605
+ =item $bool = $ast->active
606
+
607
+ True if the subtest is active. The subtest is active if its hub appears in the
608
+ global hub stack. This is true when C<< $ast->run(...) >> us running.
609
+
610
+ =item $arrayref = $ast->children
611
+
612
+ Get an arrayref of child processes/threads. Numerical items are PIDs, blessed
613
+ items are L<threads> instances.
614
+
615
+ =item $arrayref = $ast->events
616
+
617
+ Get an arrayref of events that have been sent to the subtests hub.
618
+
619
+ =item $bool = $ast->finished
620
+
621
+ True if C<finished()> has already been called.
622
+
623
+ =item $hub = $ast->hub
624
+
625
+ The hub created for the subtest.
626
+
627
+ =item $int = $ast->id
628
+
629
+ Attach/Detach counter. Used internally, not useful to users.
630
+
631
+ =item $str = $ast->name
632
+
633
+ Name of the subtest.
634
+
635
+ =item $pid = $ast->pid
636
+
637
+ PID in which the subtest was created.
638
+
639
+ =item $tid = $ast->tid
640
+
641
+ Thread ID in which the subtest was created.
642
+
643
+ =item $hub = $ast->send_to
644
+
645
+ Hub to which the final subtest event should be sent.
646
+
647
+ =item $arrayref = $ast->stack
648
+
649
+ Stack of async subtests at the time this one was created. This is mainly for
650
+ internal use.
651
+
652
+ =item $trace = $ast->trace
653
+
654
+ L<Test2::Util::Trace> instance used for error reporting.
655
+
656
+ =back
657
+
658
+ =head2 INTERFACE
659
+
660
+ =over 4
661
+
662
+ =item $ast->attach($id)
663
+
664
+ Attach a subtest in a child/process to the original.
665
+
666
+ B<Note:> C<< my $id = $ast->cleave >> must have been called in the parent
667
+ process/thread before the child was started, the id it returns must be used in
668
+ the call to C<< $ast->attach($id) >>
669
+
670
+ =item $id = $ast->cleave
671
+
672
+ Prepare a slot for a child process/thread to attach. This must be called BEFORE
673
+ the child process or thread is started. The ID returned is used by C<attach()>.
674
+
675
+ This must only be called in the original process/thread.
676
+
677
+ =item $ctx = $ast->context
678
+
679
+ Get an L<Test2::API::Context> instance that can be used to send events to the
680
+ context in which the hub was created. This is not a canonical context, you
681
+ should not call C<< $ctx->release >> on it.
682
+
683
+ =item $ast->detach
684
+
685
+ Detach from the parent in a child process/thread. This should be called just
686
+ before the child exits.
687
+
688
+ =item $ast->finish
689
+
690
+ =item $ast->finish(%options)
691
+
692
+ Finish the subtest, wait on children, and send the final subtest event.
693
+
694
+ This must only be called in the original process/thread.
695
+
696
+ B<Note:> This calls C<< $ast->wait >>.
697
+
698
+ These are the options:
699
+
700
+ =over 4
701
+
702
+ =item collapse => 1
703
+
704
+ This intelligently allows a subtest to be empty.
705
+
706
+ If no events bump the test count then the subtest no final plan will be added.
707
+ The subtest will not be considered a failure (normally an empty subtest is a
708
+ failure).
709
+
710
+ If there are no events at all the subtest will be collapsed into an
711
+ L<Test2::Event::Ok> event.
712
+
713
+ =item silent => 1
714
+
715
+ This will prevent finish from generating a final L<Test2::Event::Subtest>
716
+ event. This effectively ends the subtest without it affecting the parent
717
+ subtest (or top level test).
718
+
719
+ =item no_plan => 1
720
+
721
+ This will prevent a final plan from being added to the subtest for you when
722
+ none is directly specified.
723
+
724
+ =item skip => "reason"
725
+
726
+ This will issue an L<Test2::Event::Skip> instead of a subtest. This will throw
727
+ an exception if any events have been seen, or if state implies events have
728
+ occurred.
729
+
730
+ =back
731
+
732
+ =item $out = $ast->fork
733
+
734
+ This is a slightly higher level interface to fork. Running it will fork your
735
+ code in-place just like C<fork()>. It will return a pid in the parent, and an
736
+ L<Test2::Util::Guard> instance in the child. An exception will be thrown if
737
+ fork fails.
738
+
739
+ It is recommended that you use C<< $ast->run_fork(sub { ... }) >> instead.
740
+
741
+ =item $bool = $ast->pending
742
+
743
+ True if there are child processes, threads, or subtests that depend on this
744
+ one.
745
+
746
+ =item $bool = $ast->ready
747
+
748
+ This is essentially C<< !$ast->pending >>.
749
+
750
+ =item $ast->run(sub { ... })
751
+
752
+ Run the provided codeblock inside the subtest. This will push the subtest hub
753
+ onto the stack, run the code, then pop the hub off the stack.
754
+
755
+ =item $pid = $ast->run_fork(sub { ... })
756
+
757
+ Same as C<< $ast->run() >>, except that the codeblock is run in a child
758
+ process.
759
+
760
+ You do not need to directly call C<wait($pid)>, that will be done for you when
761
+ C<< $ast->wait >>, or C<< $ast->finish >> are called.
762
+
763
+ =item my $thr = $ast->run_thread(sub { ... });
764
+
765
+ B<** DISCOURAGED **> Threads cause problems. This method remains for anyone who
766
+ REALLY wants it, but it is no longer supported. Tests for this functionality do
767
+ not even run unless the AUTHOR_TESTING or T2_DO_THREAD_TESTS env vars are
768
+ enabled.
769
+
770
+ Same as C<< $ast->run() >>, except that the codeblock is run in a child
771
+ thread.
772
+
773
+ You do not need to directly call C<< $thr->join >>, that is done for you when
774
+ C<< $ast->wait >>, or C<< $ast->finish >> are called.
775
+
776
+ =item $passing = $ast->start
777
+
778
+ Push the subtest hub onto the stack. Returns the current pass/fail status of
779
+ the subtest.
780
+
781
+ =item $ast->stop
782
+
783
+ Pop the subtest hub off the stack. Returns the current pass/fail status of the
784
+ subtest.
785
+
786
+ =item $ast->wait
787
+
788
+ Wait on all threads/processes that were started using C<< $ast->fork >>,
789
+ C<< $ast->run_fork >>, or C<< $ast->run_thread >>.
790
+
791
+ =back
792
+
793
+ =head1 SOURCE
794
+
795
+ The source code repository for Test2-AsyncSubtest can be found at
796
+ F<https://github.com/Test-More/test-more/>.
797
+
798
+ =head1 MAINTAINERS
799
+
800
+ =over 4
801
+
802
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
803
+
804
+ =back
805
+
806
+ =head1 AUTHORS
807
+
808
+ =over 4
809
+
810
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
811
+
812
+ =back
813
+
814
+ =head1 COPYRIGHT
815
+
816
+ Copyright Chad Granum E<lt>exodist7@gmail.comE<gt>.
817
+
818
+ This program is free software; you can redistribute it and/or
819
+ modify it under the same terms as Perl itself.
820
+
821
+ See F<http://dev.perl.org/licenses/>
822
+
823
+ =cut
git/usr/share/perl5/core_perl/Test2/Bundle.pm ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::Bundle;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '1.302210';
6
+
7
+ 1;
8
+
9
+ __END__
10
+
11
+ =pod
12
+
13
+ =encoding UTF-8
14
+
15
+ =head1 NAME
16
+
17
+ Test2::Bundle - Documentation for bundles.
18
+
19
+ =head1 DESCRIPTION
20
+
21
+ Bundles are collections of Tools and Plugins. Bundles should not provide any
22
+ tools or behaviors of their own, they should simply combine the tools and
23
+ behaviors of other packages.
24
+
25
+ =head1 FAQ
26
+
27
+ =over 4
28
+
29
+ =item Should my bundle subclass Test2::Bundle?
30
+
31
+ No. Currently this class is empty. Eventually we may want to add behavior, in
32
+ which case we do not want anyone to already be subclassing it.
33
+
34
+ =back
35
+
36
+ =head1 HOW DO I WRITE A BUNDLE?
37
+
38
+ Writing a bundle can be very simple:
39
+
40
+ package Test2::Bundle::MyBundle;
41
+ use strict;
42
+ use warnings;
43
+
44
+ use Test2::Plugin::ExitSummary; # Load a plugin
45
+
46
+ use Test2::Tools::Basic qw/ok plan done_testing/;
47
+
48
+ # Re-export the tools
49
+ our @EXPORTS = qw/ok plan done_testing/;
50
+ use base 'Exporter';
51
+
52
+ 1;
53
+
54
+ If you want to do anything more complex you should look into L<Import::Into>
55
+ and L<Symbol::Move>.
56
+
57
+ =head1 SOURCE
58
+
59
+ The source code repository for Test2-Suite can be found at
60
+ F<https://github.com/Test-More/test-more/>.
61
+
62
+ =head1 MAINTAINERS
63
+
64
+ =over 4
65
+
66
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
67
+
68
+ =back
69
+
70
+ =head1 AUTHORS
71
+
72
+ =over 4
73
+
74
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
75
+
76
+ =back
77
+
78
+ =head1 COPYRIGHT
79
+
80
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
81
+
82
+ This program is free software; you can redistribute it and/or
83
+ modify it under the same terms as Perl itself.
84
+
85
+ See F<http://dev.perl.org/licenses/>
86
+
87
+ =cut
git/usr/share/perl5/core_perl/Test2/Compare.pm ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::Compare;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '1.302210';
6
+
7
+ use Scalar::Util qw/blessed/;
8
+ use Test2::Util qw/try/;
9
+ use Test2::Util::Ref qw/rtype/;
10
+
11
+ use Carp qw/croak/;
12
+
13
+ our @EXPORT_OK = qw{
14
+ compare
15
+ get_build push_build pop_build build
16
+ strict_convert relaxed_convert convert
17
+ };
18
+ use base 'Exporter';
19
+
20
+ sub compare {
21
+ my ($got, $check, $convert) = @_;
22
+
23
+ $check = $convert->($check);
24
+
25
+ return $check->run(
26
+ id => undef,
27
+ got => $got,
28
+ exists => 1,
29
+ convert => $convert,
30
+ seen => {},
31
+ );
32
+ }
33
+
34
+ my @BUILD;
35
+
36
+ sub get_build { @BUILD ? $BUILD[-1] : undef }
37
+ sub push_build { push @BUILD => $_[0] }
38
+
39
+ sub pop_build {
40
+ return pop @BUILD if @BUILD && $_[0] && $BUILD[-1] == $_[0];
41
+ my $have = @BUILD ? "$BUILD[-1]" : 'undef';
42
+ my $want = $_[0] ? "$_[0]" : 'undef';
43
+ croak "INTERNAL ERROR: Attempted to pop incorrect build, have $have, tried to pop $want";
44
+ }
45
+
46
+ sub build {
47
+ my ($class, $code) = @_;
48
+
49
+ my @caller = caller(1);
50
+
51
+ die "'$caller[3]\()' should not be called in void context in $caller[1] line $caller[2]\n"
52
+ unless defined(wantarray);
53
+
54
+ my $build = $class->new(builder => $code, called => \@caller);
55
+
56
+ push @BUILD => $build;
57
+ my ($ok, $err) = try { $code->($build); 1 };
58
+ pop @BUILD;
59
+ die $err unless $ok;
60
+
61
+ return $build;
62
+ }
63
+
64
+ sub strict_convert { convert($_[0], { implicit_end => 1, use_regex => 0, use_code => 0 }) }
65
+ sub relaxed_convert { convert($_[0], { implicit_end => 0, use_regex => 1, use_code => 1 }) }
66
+
67
+ my $CONVERT_LOADED = 0;
68
+ my %ALLOWED_KEYS = ( implicit_end => 1, use_regex => 1, use_code => 1 );
69
+ sub convert {
70
+ my ($thing, $config) = @_;
71
+
72
+ unless($CONVERT_LOADED) {
73
+ require Test2::Compare::Array;
74
+ require Test2::Compare::Base;
75
+ require Test2::Compare::Custom;
76
+ require Test2::Compare::DeepRef;
77
+ require Test2::Compare::Hash;
78
+ require Test2::Compare::Pattern;
79
+ require Test2::Compare::Ref;
80
+ require Test2::Compare::Regex;
81
+ require Test2::Compare::Scalar;
82
+ require Test2::Compare::String;
83
+ require Test2::Compare::Undef;
84
+ require Test2::Compare::Wildcard;
85
+ $CONVERT_LOADED = 1;
86
+ }
87
+
88
+ if (ref($config)) {
89
+ my $bad = join ', ' => grep { !$ALLOWED_KEYS{$_} } keys %$config;
90
+ croak "The following config options are not understood by convert(): $bad" if $bad;
91
+ $config->{implicit_end} = 1 unless defined $config->{implicit_end};
92
+ $config->{use_regex} = 1 unless defined $config->{use_regex};
93
+ $config->{use_code} = 0 unless defined $config->{use_code};
94
+ }
95
+ else { # Legacy...
96
+ if ($config) {
97
+ $config = {
98
+ implicit_end => 1,
99
+ use_regex => 0,
100
+ use_code => 0,
101
+ };
102
+ }
103
+ else {
104
+ $config = {
105
+ implicit_end => 0,
106
+ use_regex => 1,
107
+ use_code => 1,
108
+ };
109
+ }
110
+ }
111
+
112
+ return _convert($thing, $config);
113
+ }
114
+
115
+ sub _convert {
116
+ my ($thing, $config) = @_;
117
+
118
+ return Test2::Compare::Undef->new()
119
+ unless defined $thing;
120
+
121
+ if (blessed($thing) && $thing->isa('Test2::Compare::Base')) {
122
+ if ($config->{implicit_end} && $thing->can('set_ending') && !defined $thing->ending) {
123
+ my $clone = $thing->clone;
124
+ $clone->set_ending('implicit');
125
+ return $clone;
126
+ }
127
+
128
+ return $thing unless $thing->isa('Test2::Compare::Wildcard');
129
+ my $newthing = _convert($thing->expect, $config);
130
+ $newthing->set_builder($thing->builder) unless $newthing->builder;
131
+ $newthing->set_file($thing->_file) unless $newthing->_file;
132
+ $newthing->set_lines($thing->_lines) unless $newthing->_lines;
133
+ return $newthing;
134
+ }
135
+
136
+ my $type = rtype($thing);
137
+
138
+ return Test2::Compare::Array->new(inref => $thing, $config->{implicit_end} ? (ending => 1) : ())
139
+ if $type eq 'ARRAY';
140
+
141
+ return Test2::Compare::Hash->new(inref => $thing, $config->{implicit_end} ? (ending => 1) : ())
142
+ if $type eq 'HASH';
143
+
144
+ return Test2::Compare::Pattern->new(
145
+ pattern => $thing,
146
+ stringify_got => 1,
147
+ ) if $config->{use_regex} && $type eq 'REGEXP';
148
+
149
+ return Test2::Compare::Custom->new(code => $thing)
150
+ if $config->{use_code} && $type eq 'CODE';
151
+
152
+ return Test2::Compare::Regex->new(input => $thing)
153
+ if $type eq 'REGEXP';
154
+
155
+ if ($type eq 'SCALAR' || $type eq 'VSTRING') {
156
+ my $nested = _convert($$thing, $config);
157
+ return Test2::Compare::Scalar->new(item => $nested);
158
+ }
159
+
160
+ return Test2::Compare::DeepRef->new(input => $thing)
161
+ if $type eq 'REF';
162
+
163
+ return Test2::Compare::Ref->new(input => $thing)
164
+ if $type;
165
+
166
+ # is() will assume string and use 'eq'
167
+ return Test2::Compare::String->new(input => $thing);
168
+ }
169
+
170
+ 1;
171
+
172
+ __END__
173
+
174
+ =pod
175
+
176
+ =encoding UTF-8
177
+
178
+ =head1 NAME
179
+
180
+ Test2::Compare - Test2 extension for writing deep comparison tools.
181
+
182
+ =head1 DESCRIPTION
183
+
184
+ This library is the driving force behind deep comparison tools such as
185
+ C<Test2::Tools::Compare::is()> and
186
+ C<Test2::Tools::ClassicCompare::is_deeply()>.
187
+
188
+ =head1 SYNOPSIS
189
+
190
+ package Test2::Tools::MyCheck;
191
+
192
+ use Test2::Compare::MyCheck;
193
+ use Test2::Compare qw/compare/;
194
+
195
+ sub MyCheck {
196
+ my ($got, $exp, $name, @diag) = @_;
197
+ my $ctx = context();
198
+
199
+ my $delta = compare($got, $exp, \&convert);
200
+
201
+ if ($delta) {
202
+ $ctx->fail($name, $delta->diag, @diag);
203
+ }
204
+ else {
205
+ $ctx->ok(1, $name);
206
+ }
207
+
208
+ $ctx->release;
209
+ return !$delta;
210
+ }
211
+
212
+ sub convert {
213
+ my $thing = shift;
214
+ return $thing if blessed($thing) && $thing->isa('Test2::Compare::MyCheck');
215
+
216
+ return Test2::Compare::MyCheck->new(stuff => $thing);
217
+ }
218
+
219
+ See L<Test2::Compare::Base> for details about writing a custom check.
220
+
221
+ =head1 EXPORTS
222
+
223
+ =over 4
224
+
225
+ =item $delta = compare($got, $expect, \&convert)
226
+
227
+ This will compare the structures in C<$got> with those in C<$expect>, The
228
+ convert sub should convert vanilla structures inside C<$expect> into checks.
229
+ If there are differences in the structures they will be reported back as an
230
+ L<Test2::Compare::Delta> tree.
231
+
232
+ =item $build = get_build()
233
+
234
+ Get the current global build, if any.
235
+
236
+ =item push_build($build)
237
+
238
+ Set the current global build.
239
+
240
+ =item $build = pop_build($build)
241
+
242
+ Unset the current global build. This will throw an exception if the build
243
+ passed in is different from the current global.
244
+
245
+ =item build($class, sub { ... })
246
+
247
+ Run the provided codeblock with a new instance of C<$class> as the current
248
+ build. Returns the new build.
249
+
250
+ =item $check = convert($thing)
251
+
252
+ =item $check = convert($thing, $config)
253
+
254
+ This convert function is used by C<strict_convert()> and C<relaxed_convert()>
255
+ under the hood. It can also be used as the basis for other convert functions.
256
+
257
+ If you want to use it with a custom configuration you should wrap it in another
258
+ sub like so:
259
+
260
+ sub my_convert {
261
+ my $thing_to_convert = shift;
262
+ return convert(
263
+ $thing_to_convert,
264
+ { ... }
265
+ );
266
+ }
267
+
268
+ Or the short variant:
269
+
270
+ sub my_convert { convert($_[0], { ... }) }
271
+
272
+ There are several configuration options, here they are with the default setting
273
+ listed first:
274
+
275
+ =over 4
276
+
277
+ =item implicit_end => 1
278
+
279
+ This option toggles array/hash boundaries. If this is true then no extra hash
280
+ keys or array indexes will be allowed. This setting affects generated compare
281
+ objects as well as any passed in.
282
+
283
+ =item use_regex => 1
284
+
285
+ This option toggles regex matching. When true (default) regexes are converted
286
+ to checks such that values must match the regex. When false regexes will be
287
+ compared to see if they are identical regexes.
288
+
289
+ =item use_code => 0
290
+
291
+ This option toggles code matching. When false (default) coderefs in structures
292
+ must be the same coderef as specified. When true coderefs will be run to verify
293
+ the value being checked.
294
+
295
+ =back
296
+
297
+ =item $check = strict_convert($thing)
298
+
299
+ Convert C<$thing> to an L<Test2::Compare::*> object. This will behave strictly
300
+ which means it uses these settings:
301
+
302
+ =over 4
303
+
304
+ =item implicit_end => 1
305
+
306
+ Array bounds will be checked when this object is used in a comparison. No
307
+ unexpected hash keys can be present.
308
+
309
+ =item use_code => 0
310
+
311
+ Sub references will be compared as refs (IE are these sub refs the same ref?)
312
+
313
+ =item use_regex => 0
314
+
315
+ Regexes will be compared directly (IE are the regexes the same?)
316
+
317
+ =back
318
+
319
+ =item $compare = relaxed_convert($thing)
320
+
321
+ Convert C<$thing> to an L<Test2::Compare::*> object. This will be relaxed which
322
+ means it uses these settings:
323
+
324
+ =over 4
325
+
326
+ =item implicit_end => 0
327
+
328
+ Array bounds will not be checked when this object is used in a comparison.
329
+ Unexpected hash keys can be present.
330
+
331
+ =item use_code => 1
332
+
333
+ Sub references will be run to verify a value.
334
+
335
+ =item use_regex => 1
336
+
337
+ Values will be checked against any regexes provided.
338
+
339
+ =back
340
+
341
+ =back
342
+
343
+ =head1 WRITING A VARIANT OF IS/LIKE
344
+
345
+ use Test2::Compare qw/compare convert/;
346
+
347
+ sub my_like($$;$@) {
348
+ my ($got, $exp, $name, @diag) = @_;
349
+ my $ctx = context();
350
+
351
+ # A custom converter that does the same thing as the one used by like()
352
+ my $convert = sub {
353
+ my $thing = shift;
354
+ return convert(
355
+ $thing,
356
+ {
357
+ implicit_end => 0,
358
+ use_code => 1,
359
+ use_regex => 1,
360
+ }
361
+ );
362
+ };
363
+
364
+ my $delta = compare($got, $exp, $convert);
365
+
366
+ if ($delta) {
367
+ $ctx->fail($name, $delta->diag, @diag);
368
+ }
369
+ else {
370
+ $ctx->ok(1, $name);
371
+ }
372
+
373
+ $ctx->release;
374
+ return !$delta;
375
+ }
376
+
377
+ The work of a comparison tool is done by 3 entities:
378
+
379
+ =over 4
380
+
381
+ =item compare()
382
+
383
+ The C<compare()> function takes the structure you got, the specification you
384
+ want to check against, and a C<\&convert> sub that will convert anything that
385
+ is not an instance of an L<Test2::Compare::Base> subclass into one.
386
+
387
+ This tool will use the C<\&convert> function on the specification, and then
388
+ produce an L<Test2::Compare::Delta> structure that outlines all the ways the
389
+ structure you got deviates from the specification.
390
+
391
+ =item \&convert
392
+
393
+ Converts anything that is not an instance of an L<Test2::Compare::Base>
394
+ subclass, and turns it into one. The objects this produces are able to check
395
+ that a structure matches a specification.
396
+
397
+ =item $delta
398
+
399
+ An instance of L<Test2::Compare::Delta> is ultimately returned. This object
400
+ represents all the ways in with the structure you got deviated from the
401
+ specification. The delta is a tree and may contain child deltas for nested
402
+ structures.
403
+
404
+ The delta is capable of rendering itself as a table, use C<< @lines =
405
+ $delta->diag >> to get the table (lines in C<@lines> will not be terminated
406
+ with C<"\n">).
407
+
408
+ =back
409
+
410
+ The C<convert()> function provided by this package contains all the
411
+ specification behavior of C<like()> and C<is()>. It is intended to be wrapped
412
+ in a sub that passes in a configuration hash, which allows you to control the
413
+ behavior.
414
+
415
+ You are free to write your own C<$check = compare($thing)> function, it just
416
+ needs to accept a single argument, and produce a single instance of an
417
+ L<Test2::Compare::Base> subclass.
418
+
419
+ =head1 SOURCE
420
+
421
+ The source code repository for Test2-Suite can be found at
422
+ F<https://github.com/Test-More/test-more/>.
423
+
424
+ =head1 MAINTAINERS
425
+
426
+ =over 4
427
+
428
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
429
+
430
+ =back
431
+
432
+ =head1 AUTHORS
433
+
434
+ =over 4
435
+
436
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
437
+
438
+ =back
439
+
440
+ =head1 COPYRIGHT
441
+
442
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
443
+
444
+ This program is free software; you can redistribute it and/or
445
+ modify it under the same terms as Perl itself.
446
+
447
+ See F<http://dev.perl.org/licenses/>
448
+
449
+ =cut
git/usr/share/perl5/core_perl/Test2/Env.pm ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::Env;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '1.302210';
6
+
7
+ 1;
8
+
9
+ __END__
10
+
11
+ =pod
12
+
13
+ =encoding UTF-8
14
+
15
+ =head1 NAME
16
+
17
+ Test2::Env - Documentation for environment variables used or set by Test2.
18
+
19
+ =head1 DESCRIPTION
20
+
21
+ This is a list of environment variables that are either set by, or read by Test2.
22
+
23
+ =head1 AUTHOR_TESTING
24
+
25
+ This env var is read by Test2. When set Test2 will run tests that are normally
26
+ skipped unless a module author is doing extra author-specific testing.
27
+
28
+ =head1 AUTOMATED_TESTING
29
+
30
+ This env var is read by Test2. When set this indicates the tests are run by an
31
+ automated system and no human interaction is possible.
32
+
33
+ See L<Test2::Require::AuthorTesting>.
34
+
35
+ =head1 EXTENDED_TESTING
36
+
37
+ This env var is read by Test2. When set it indicates some extended testing that
38
+ should normally be skipped will be run.
39
+
40
+ See L<Test2::Require::ExtendedTesting>.
41
+
42
+ =head1 HARNESS_ACTIVE
43
+
44
+ This env var is read by Test2. It is usually set by C<prove> (L<Test::Harness>)
45
+ or C<yath> (L<App::Yath>).
46
+
47
+ =head1 NONINTERACTIVE_TESTING
48
+
49
+ This env var is read by Test2. When set this indicates the testing will not be
50
+ interactive.
51
+
52
+ See L<Test2::Require::NonInteractiveTesting>.
53
+
54
+ =head1 RELEASE_TESTING
55
+
56
+ This env var is read by Test2. When set this indicates that release testing is
57
+ being done, which may run more tests than normal.
58
+
59
+ See L<Test2::Require::ReleaseTesting>.
60
+
61
+ =head1 T2_FORMATTER
62
+
63
+ This can be used to set the formatter that Test2 will use. If set to a string
64
+ without a '+' prefix, then 'Test2::Formatter::' will be added to the start of
65
+ the module name. If '+' is present it will be stripped and no further
66
+ modification will be made to the module name.
67
+
68
+ =head1 T2_IN_PRELOAD
69
+
70
+ Test2 sets this when preload mode is active. This is mainly used by
71
+ L<App::Yath> and similar tools that preload Test2, then fork to run tests.
72
+
73
+ =head1 TABLE_TERM_SIZE
74
+
75
+ This is used to set a terminal width for things like diagnostic message tables.
76
+
77
+ =head1 TEST2_ACTIVE
78
+
79
+ Test2 sets this variable when tests are running.
80
+
81
+ =head1 TEST2_ENABLE_PLUGINS
82
+
83
+ This can be used to force plugins to be loaded whent he Test2 API is loaded. It
84
+ takes a list of one or more plugin names seperated by comma. If the module name
85
+ does not have a '+' in front of it then the C<Test2::Plugin::> namespace is
86
+ assumed and added. If a '+' is present at the start of a module name it will be
87
+ stripped and no further modification will be made.
88
+
89
+ Examples:
90
+
91
+ TEST2_ENABLE_PLUGINS=BailOnFail
92
+ Test2_ENABLE_PLUGINS=SRand,+My::Plugin::Name
93
+
94
+ =head1 TEST_ACTIVE
95
+
96
+ Set by Test2 when tests are running.
97
+
98
+ =head1 TS_MAX_DELTA
99
+
100
+ Used to determine how many max lines of output will be provided when is() finds
101
+ a deep data strucgture mismatch.
102
+
103
+ =head1 SOURCE
104
+
105
+ The source code repository for Test2-Suite can be found at
106
+ F<https://github.com/Test-More/test-more/>.
107
+
108
+ =head1 MAINTAINERS
109
+
110
+ =over 4
111
+
112
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
113
+
114
+ =back
115
+
116
+ =head1 AUTHORS
117
+
118
+ =over 4
119
+
120
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
121
+
122
+ =back
123
+
124
+ =head1 COPYRIGHT
125
+
126
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
127
+
128
+ This program is free software; you can redistribute it and/or
129
+ modify it under the same terms as Perl itself.
130
+
131
+ See F<http://dev.perl.org/licenses/>
132
+
133
+ =cut
git/usr/share/perl5/core_perl/Test2/Event.pm ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::Event;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '1.302210';
6
+
7
+ use Scalar::Util qw/blessed reftype/;
8
+ use Carp qw/croak/;
9
+
10
+ use Test2::Util::HashBase qw/trace -amnesty uuid -_eid -hubs/;
11
+ use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/;
12
+ use Test2::Util qw/pkg_to_file gen_uid/;
13
+
14
+ use Test2::EventFacet::About();
15
+ use Test2::EventFacet::Amnesty();
16
+ use Test2::EventFacet::Assert();
17
+ use Test2::EventFacet::Control();
18
+ use Test2::EventFacet::Error();
19
+ use Test2::EventFacet::Info();
20
+ use Test2::EventFacet::Meta();
21
+ use Test2::EventFacet::Parent();
22
+ use Test2::EventFacet::Plan();
23
+ use Test2::EventFacet::Trace();
24
+ use Test2::EventFacet::Hub();
25
+
26
+ # Legacy tools will expect this to be loaded now
27
+ require Test2::Util::Trace;
28
+
29
+ my %LOADED_FACETS = (
30
+ 'about' => 'Test2::EventFacet::About',
31
+ 'amnesty' => 'Test2::EventFacet::Amnesty',
32
+ 'assert' => 'Test2::EventFacet::Assert',
33
+ 'control' => 'Test2::EventFacet::Control',
34
+ 'errors' => 'Test2::EventFacet::Error',
35
+ 'info' => 'Test2::EventFacet::Info',
36
+ 'meta' => 'Test2::EventFacet::Meta',
37
+ 'parent' => 'Test2::EventFacet::Parent',
38
+ 'plan' => 'Test2::EventFacet::Plan',
39
+ 'trace' => 'Test2::EventFacet::Trace',
40
+ 'hubs' => 'Test2::EventFacet::Hub',
41
+ );
42
+
43
+ sub FACET_TYPES { sort values %LOADED_FACETS }
44
+
45
+ sub load_facet {
46
+ my $class = shift;
47
+ my ($facet) = @_;
48
+
49
+ return $LOADED_FACETS{$facet} if exists $LOADED_FACETS{$facet};
50
+
51
+ my @check = ($facet);
52
+ if ('s' eq substr($facet, -1, 1)) {
53
+ push @check => substr($facet, 0, -1);
54
+ }
55
+ else {
56
+ push @check => $facet . 's';
57
+ }
58
+
59
+ my $found;
60
+ for my $check (@check) {
61
+ my $mod = "Test2::EventFacet::" . ucfirst($facet);
62
+ my $file = pkg_to_file($mod);
63
+ next unless eval { require $file; 1 };
64
+ $found = $mod;
65
+ last;
66
+ }
67
+
68
+ return undef unless $found;
69
+ $LOADED_FACETS{$facet} = $found;
70
+ }
71
+
72
+ sub causes_fail { 0 }
73
+ sub increments_count { 0 }
74
+ sub diagnostics { 0 }
75
+ sub no_display { 0 }
76
+ sub subtest_id { undef }
77
+
78
+ sub callback { }
79
+
80
+ sub terminate { () }
81
+ sub global { () }
82
+ sub sets_plan { () }
83
+
84
+ sub summary { ref($_[0]) }
85
+
86
+ sub related {
87
+ my $self = shift;
88
+ my ($event) = @_;
89
+
90
+ my $tracea = $self->trace or return undef;
91
+ my $traceb = $event->trace or return undef;
92
+
93
+ my $uuida = $tracea->uuid;
94
+ my $uuidb = $traceb->uuid;
95
+ if ($uuida && $uuidb) {
96
+ return 1 if $uuida eq $uuidb;
97
+ return 0;
98
+ }
99
+
100
+ my $siga = $tracea->signature or return undef;
101
+ my $sigb = $traceb->signature or return undef;
102
+
103
+ return 1 if $siga eq $sigb;
104
+ return 0;
105
+ }
106
+
107
+ sub add_hub {
108
+ my $self = shift;
109
+ unshift @{$self->{+HUBS}} => @_;
110
+ }
111
+
112
+ sub add_amnesty {
113
+ my $self = shift;
114
+
115
+ for my $am (@_) {
116
+ $am = {%$am} if ref($am) ne 'ARRAY';
117
+ $am = Test2::EventFacet::Amnesty->new($am);
118
+
119
+ push @{$self->{+AMNESTY}} => $am;
120
+ }
121
+ }
122
+
123
+ sub eid { $_[0]->{+_EID} ||= gen_uid() }
124
+
125
+ sub common_facet_data {
126
+ my $self = shift;
127
+
128
+ my %out;
129
+
130
+ $out{about} = {package => ref($self) || undef};
131
+ if (my $uuid = $self->uuid) {
132
+ $out{about}->{uuid} = $uuid;
133
+ }
134
+
135
+ $out{about}->{eid} = $self->{+_EID} || $self->eid;
136
+
137
+ if (my $trace = $self->trace) {
138
+ $out{trace} = { %$trace };
139
+ }
140
+
141
+ if (my $hubs = $self->hubs) {
142
+ $out{hubs} = $hubs;
143
+ }
144
+
145
+ $out{amnesty} = [map {{ %{$_} }} @{$self->{+AMNESTY}}]
146
+ if $self->{+AMNESTY};
147
+
148
+ if (my $meta = $self->meta_facet_data) {
149
+ $out{meta} = $meta;
150
+ }
151
+
152
+ return \%out;
153
+ }
154
+
155
+ sub meta_facet_data {
156
+ my $self = shift;
157
+
158
+ my $key = Test2::Util::ExternalMeta::META_KEY();
159
+
160
+ my $hash = $self->{$key} or return undef;
161
+ return {%$hash};
162
+ }
163
+
164
+ sub facet_data {
165
+ my $self = shift;
166
+
167
+ my $out = $self->common_facet_data;
168
+
169
+ $out->{about}->{details} = $self->summary || undef;
170
+ $out->{about}->{no_display} = $self->no_display || undef;
171
+
172
+ # Might be undef, we want to preserve that
173
+ my $terminate = $self->terminate;
174
+ $out->{control} = {
175
+ global => $self->global || 0,
176
+ terminate => $terminate,
177
+ has_callback => $self->can('callback') == \&callback ? 0 : 1,
178
+ };
179
+
180
+ $out->{assert} = {
181
+ no_debug => 1, # Legacy behavior
182
+ pass => $self->causes_fail ? 0 : 1,
183
+ details => $self->summary,
184
+ } if $self->increments_count;
185
+
186
+ $out->{parent} = {hid => $self->subtest_id} if $self->subtest_id;
187
+
188
+ if (my @plan = $self->sets_plan) {
189
+ $out->{plan} = {};
190
+
191
+ $out->{plan}->{count} = $plan[0] if defined $plan[0];
192
+ $out->{plan}->{details} = $plan[2] if defined $plan[2];
193
+
194
+ if ($plan[1]) {
195
+ $out->{plan}->{skip} = 1 if $plan[1] eq 'SKIP';
196
+ $out->{plan}->{none} = 1 if $plan[1] eq 'NO PLAN';
197
+ }
198
+
199
+ $out->{control}->{terminate} ||= 0 if $out->{plan}->{skip};
200
+ }
201
+
202
+ if ($self->causes_fail && !$out->{assert}) {
203
+ $out->{errors} = [
204
+ {
205
+ tag => 'FAIL',
206
+ fail => 1,
207
+ details => $self->summary,
208
+ }
209
+ ];
210
+ }
211
+
212
+ my %IGNORE = (trace => 1, about => 1, control => 1);
213
+ my $do_info = !grep { !$IGNORE{$_} } keys %$out;
214
+
215
+ if ($do_info && !$self->no_display && $self->diagnostics) {
216
+ $out->{info} = [
217
+ {
218
+ tag => 'DIAG',
219
+ debug => 1,
220
+ details => $self->summary,
221
+ }
222
+ ];
223
+ }
224
+
225
+ return $out;
226
+ }
227
+
228
+ sub facets {
229
+ my $self = shift;
230
+ my %out;
231
+
232
+ my $data = $self->facet_data;
233
+ my @errors = $self->validate_facet_data($data);
234
+ die join "\n" => @errors if @errors;
235
+
236
+ for my $facet (keys %$data) {
237
+ my $class = $self->load_facet($facet);
238
+ my $val = $data->{$facet};
239
+
240
+ unless($class) {
241
+ $out{$facet} = $val;
242
+ next;
243
+ }
244
+
245
+ my $is_list = reftype($val) eq 'ARRAY' ? 1 : 0;
246
+ if ($is_list) {
247
+ $out{$facet} = [map { $class->new($_) } @$val];
248
+ }
249
+ else {
250
+ $out{$facet} = $class->new($val);
251
+ }
252
+ }
253
+
254
+ return \%out;
255
+ }
256
+
257
+ sub validate_facet_data {
258
+ my $class_or_self = shift;
259
+ my ($f, %params);
260
+
261
+ $f = shift if @_ && (reftype($_[0]) || '') eq 'HASH';
262
+ %params = @_;
263
+
264
+ $f ||= $class_or_self->facet_data if blessed($class_or_self);
265
+ croak "No facet data" unless $f;
266
+
267
+ my @errors;
268
+
269
+ for my $k (sort keys %$f) {
270
+ my $fclass = $class_or_self->load_facet($k);
271
+
272
+ push @errors => "Could not find a facet class for facet '$k'"
273
+ if $params{require_facet_class} && !$fclass;
274
+
275
+ next unless $fclass;
276
+
277
+ my $v = $f->{$k};
278
+ next unless defined($v); # undef is always fine
279
+
280
+ my $is_list = $fclass->is_list();
281
+ my $got_list = reftype($v) eq 'ARRAY' ? 1 : 0;
282
+
283
+ push @errors => "Facet '$k' should be a list, but got a single item ($v)"
284
+ if $is_list && !$got_list;
285
+
286
+ push @errors => "Facet '$k' should not be a list, but got a a list ($v)"
287
+ if $got_list && !$is_list;
288
+ }
289
+
290
+ return @errors;
291
+ }
292
+
293
+ sub nested {
294
+ my $self = shift;
295
+
296
+ Carp::cluck("Use of Test2::Event->nested() is deprecated, use Test2::Event->trace->nested instead")
297
+ if $ENV{AUTHOR_TESTING};
298
+
299
+ if (my $hubs = $self->{+HUBS}) {
300
+ return $hubs->[0]->{nested} if @$hubs;
301
+ }
302
+
303
+ my $trace = $self->{+TRACE} or return undef;
304
+ return $trace->{nested};
305
+ }
306
+
307
+ sub in_subtest {
308
+ my $self = shift;
309
+
310
+ Carp::cluck("Use of Test2::Event->in_subtest() is deprecated, use Test2::Event->trace->hid instead")
311
+ if $ENV{AUTHOR_TESTING};
312
+
313
+ my $hubs = $self->{+HUBS};
314
+ if ($hubs && @$hubs) {
315
+ return undef unless $hubs->[0]->{nested};
316
+ return $hubs->[0]->{hid}
317
+ }
318
+
319
+ my $trace = $self->{+TRACE} or return undef;
320
+ return undef unless $trace->{nested};
321
+ return $trace->{hid};
322
+ }
323
+
324
+ 1;
325
+
326
+ __END__
327
+
328
+ =pod
329
+
330
+ =encoding UTF-8
331
+
332
+ =head1 NAME
333
+
334
+ Test2::Event - Base class for events
335
+
336
+ =head1 DESCRIPTION
337
+
338
+ Base class for all event objects that get passed through
339
+ L<Test2>.
340
+
341
+ =head1 SYNOPSIS
342
+
343
+ package Test2::Event::MyEvent;
344
+ use strict;
345
+ use warnings;
346
+
347
+ # This will make our class an event subclass (required)
348
+ use base 'Test2::Event';
349
+
350
+ # Add some accessors (optional)
351
+ # You are not obligated to use HashBase, you can use any object tool you
352
+ # want, or roll your own accessors.
353
+ use Test2::Util::HashBase qw/foo bar baz/;
354
+
355
+ # Use this if you want the legacy API to be written for you, for this to
356
+ # work you will need to implement a facet_data() method.
357
+ use Test2::Util::Facets2Legacy;
358
+
359
+ # Chance to initialize some defaults
360
+ sub init {
361
+ my $self = shift;
362
+ # no other args in @_
363
+
364
+ $self->set_foo('xxx') unless defined $self->foo;
365
+
366
+ ...
367
+ }
368
+
369
+ # This is the new way for events to convey data to the Test2 system
370
+ sub facet_data {
371
+ my $self = shift;
372
+
373
+ # Get common facets such as 'about', 'trace' 'amnesty', and 'meta'
374
+ my $facet_data = $self->common_facet_data();
375
+
376
+ # Are you making an assertion?
377
+ $facet_data->{assert} = {pass => 1, details => 'my assertion'};
378
+ ...
379
+
380
+ return $facet_data;
381
+ }
382
+
383
+ 1;
384
+
385
+ =head1 METHODS
386
+
387
+ =head2 GENERAL
388
+
389
+ =over 4
390
+
391
+ =item $trace = $e->trace
392
+
393
+ Get a snapshot of the L<Test2::EventFacet::Trace> as it was when this event was
394
+ generated
395
+
396
+ =item $bool_or_undef = $e->related($e2)
397
+
398
+ Check if 2 events are related. In this case related means their traces share a
399
+ signature meaning they were created with the same context (or at the very least
400
+ by contexts which share an id, which is the same thing unless someone is doing
401
+ something very bad).
402
+
403
+ This can be used to reliably link multiple events created by the same tool. For
404
+ instance a failing test like C<ok(0, "fail"> will generate 2 events, one being
405
+ a L<Test2::Event::Ok>, the other being a L<Test2::Event::Diag>, both of these
406
+ events are related having been created under the same context and by the same
407
+ initial tool (though multiple tools may have been nested under the initial
408
+ one).
409
+
410
+ This will return C<undef> if the relationship cannot be checked, which happens
411
+ if either event has an incomplete or missing trace. This will return C<0> if
412
+ the traces are complete, but do not match. C<1> will be returned if there is a
413
+ match.
414
+
415
+ =item $e->add_amnesty({tag => $TAG, details => $DETAILS});
416
+
417
+ This can be used to add amnesty to this event. Amnesty only affects failing
418
+ assertions in most cases, but some formatters may display them for passing
419
+ assertions, or even non-assertions as well.
420
+
421
+ Amnesty will prevent a failed assertion from causing the overall test to fail.
422
+ In other words it marks a failure as expected and allowed.
423
+
424
+ B<Note:> This is how 'TODO' is implemented under the hood. TODO is essentially
425
+ amnesty with the 'TODO' tag. The details are the reason for the TODO.
426
+
427
+ =item $uuid = $e->uuid
428
+
429
+ If UUID tagging is enabled (See L<Test::API>) then any event that has made its
430
+ way through a hub will be tagged with a UUID. A newly created event will not
431
+ yet be tagged in most cases.
432
+
433
+ =item $class = $e->load_facet($name)
434
+
435
+ This method is used to load a facet by name (or key). It will attempt to load
436
+ the facet class, if it succeeds it will return the class it loaded. If it fails
437
+ it will return C<undef>. This caches the result at the class level so that
438
+ future calls will be faster.
439
+
440
+ The C<$name> variable should be the key used to access the facet in a facets
441
+ hashref. For instance the assertion facet has the key 'assert', the information
442
+ facet has the 'info' key, and the error facet has the key 'errors'. You may
443
+ include or omit the 's' at the end of the name, the method is smart enough to
444
+ try both the 's' and no-'s' forms, it will check what you provided first, and
445
+ if that is not found it will add or strip the 's and try again.
446
+
447
+ =item @classes = $e->FACET_TYPES()
448
+
449
+ =item @classes = Test2::Event->FACET_TYPES()
450
+
451
+ This returns a list of all facets that have been loaded using the
452
+ C<load_facet()> method. This will not return any classes that have not been
453
+ loaded, or have been loaded directly without a call to C<load_facet()>.
454
+
455
+ B<Note:> The core facet types are automatically loaded and populated in this
456
+ list.
457
+
458
+ =back
459
+
460
+ =head2 NEW API
461
+
462
+ =over 4
463
+
464
+ =item $hashref = $e->common_facet_data();
465
+
466
+ This can be used by subclasses to generate a starting facet data hashref. This
467
+ will populate the hashref with the trace, meta, amnesty, and about facets.
468
+ These facets are nearly always produced the same way for all events.
469
+
470
+ =item $hashref = $e->facet_data()
471
+
472
+ If you do not override this then the default implementation will attempt to
473
+ generate facets from the legacy API. This generation is limited only to what
474
+ the legacy API can provide. It is recommended that you override this method and
475
+ write out explicit facet data.
476
+
477
+ =item $hashref = $e->facets()
478
+
479
+ This takes the hashref from C<facet_data()> and blesses each facet into the
480
+ proper C<Test2::EventFacet::*> subclass. If no class can be found for any given
481
+ facet it will be passed along unchanged.
482
+
483
+ =item @errors = $e->validate_facet_data();
484
+
485
+ =item @errors = $e->validate_facet_data(%params);
486
+
487
+ =item @errors = $e->validate_facet_data(\%facets, %params);
488
+
489
+ =item @errors = Test2::Event->validate_facet_data(%params);
490
+
491
+ =item @errors = Test2::Event->validate_facet_data(\%facets, %params);
492
+
493
+ This method will validate facet data and return a list of errors. If no errors
494
+ are found this will return an empty list.
495
+
496
+ This can be called as an object method with no arguments, in which case the
497
+ C<facet_data()> method will be called to get the facet data to be validated.
498
+
499
+ When used as an object method the C<\%facet_data> argument may be omitted.
500
+
501
+ When used as a class method the C<\%facet_data> argument is required.
502
+
503
+ Remaining arguments will be slurped into a C<%params> hash.
504
+
505
+ Currently only 1 parameter is defined:
506
+
507
+ =over 4
508
+
509
+ =item require_facet_class => $BOOL
510
+
511
+ When set to true (default is false) this will reject any facets where a facet
512
+ class cannot be found. Normally facets without classes are assumed to be custom
513
+ and are ignored.
514
+
515
+ =back
516
+
517
+ =back
518
+
519
+ =head3 WHAT ARE FACETS?
520
+
521
+ Facets are how events convey their purpose to the Test2 internals and
522
+ formatters. An event without facets will have no intentional effect on the
523
+ overall test state, and will not be displayed at all by most formatters, except
524
+ perhaps to say that an event of an unknown type was seen.
525
+
526
+ Facets are produced by the C<facet_data()> subroutine, which you should
527
+ nearly-always override. C<facet_data()> is expected to return a hashref where
528
+ each key is the facet type, and the value is either a hashref with the data for
529
+ that facet, or an array of hashrefs. Some facets must be defined as single
530
+ hashrefs, some must be defined as an array of hashrefs, No facets allow both.
531
+
532
+ C<facet_data()> B<MUST NOT> bless the data it returns, the main hashref, and
533
+ nested facet hashrefs B<MUST> be bare, though items contained within each
534
+ facet may be blessed. The data returned by this method B<should> also be copies
535
+ of the internal data in order to prevent accidental state modification.
536
+
537
+ C<facets()> takes the data from C<facet_data()> and blesses it into the
538
+ C<Test2::EventFacet::*> packages. This is rarely used however, the EventFacet
539
+ packages are primarily for convenience and documentation. The EventFacet
540
+ classes are not used at all internally, instead the raw data is used.
541
+
542
+ Here is a list of facet types by package. The packages are not used internally,
543
+ but are where the documentation for each type is kept.
544
+
545
+ B<Note:> Every single facet type has the C<'details'> field. This field is
546
+ always intended for human consumption, and when provided, should explain the
547
+ 'why' for the facet. All other fields are facet specific.
548
+
549
+ =over 4
550
+
551
+ =item about => {...}
552
+
553
+ L<Test2::EventFacet::About>
554
+
555
+ This contains information about the event itself such as the event package
556
+ name. The C<details> field for this facet is an overall summary of the event.
557
+
558
+ =item assert => {...}
559
+
560
+ L<Test2::EventFacet::Assert>
561
+
562
+ This facet is used if an assertion was made. The C<details> field of this facet
563
+ is the description of the assertion.
564
+
565
+ =item control => {...}
566
+
567
+ L<Test2::EventFacet::Control>
568
+
569
+ This facet is used to tell the L<Test2::Event::Hub> about special actions the
570
+ event causes. Things like halting all testing, terminating the current test,
571
+ etc. In this facet the C<details> field explains why any special action was
572
+ taken.
573
+
574
+ B<Note:> This is how bail-out is implemented.
575
+
576
+ =item meta => {...}
577
+
578
+ L<Test2::EventFacet::Meta>
579
+
580
+ The meta facet contains all the meta-data attached to the event. In this case
581
+ the C<details> field has no special meaning, but may be present if something
582
+ sets the 'details' meta-key on the event.
583
+
584
+ =item parent => {...}
585
+
586
+ L<Test2::EventFacet::Parent>
587
+
588
+ This facet contains nested events and similar details for subtests. In this
589
+ facet the C<details> field will typically be the name of the subtest.
590
+
591
+ =item plan => {...}
592
+
593
+ L<Test2::EventFacet::Plan>
594
+
595
+ This facet tells the system that a plan has been set. The C<details> field of
596
+ this is usually left empty, but when present explains why the plan is what it
597
+ is, this is most useful if the plan is to skip-all.
598
+
599
+ =item trace => {...}
600
+
601
+ L<Test2::EventFacet::Trace>
602
+
603
+ This facet contains information related to when and where the event was
604
+ generated. This is how the test file and line number of a failure is known.
605
+ This facet can also help you to tell if tests are related.
606
+
607
+ In this facet the C<details> field overrides the "failed at test_file.t line
608
+ 42." message provided on assertion failure.
609
+
610
+ =item amnesty => [{...}, ...]
611
+
612
+ L<Test2::EventFacet::Amnesty>
613
+
614
+ The amnesty facet is a list instead of a single item, this is important as
615
+ amnesty can come from multiple places at once.
616
+
617
+ For each instance of amnesty the C<details> field explains why amnesty was
618
+ granted.
619
+
620
+ B<Note:> Outside of formatters amnesty only acts to forgive a failing
621
+ assertion.
622
+
623
+ =item errors => [{...}, ...]
624
+
625
+ L<Test2::EventFacet::Error>
626
+
627
+ The errors facet is a list instead of a single item, any number of errors can
628
+ be listed. In this facet C<details> describes the error, or may contain the raw
629
+ error message itself (such as an exception). In perl exception may be blessed
630
+ objects, as such the raw data for this facet may contain nested items which are
631
+ blessed.
632
+
633
+ Not all errors are considered fatal, there is a C<fail> field that must be set
634
+ for an error to cause the test to fail.
635
+
636
+ B<Note:> This facet is unique in that the field name is 'errors' while the
637
+ package is 'Error'. This is because this is the only facet type that is both a
638
+ list, and has a name where the plural is not the same as the singular. This may
639
+ cause some confusion, but I feel it will be less confusing than the
640
+ alternative.
641
+
642
+ =item info => [{...}, ...]
643
+
644
+ L<Test2::EventFacet::Info>
645
+
646
+ The 'info' facet is a list instead of a single item, any quantity of extra
647
+ information can be attached to an event. Some information may be critical
648
+ diagnostics, others may be simply commentary in nature, this is determined by
649
+ the C<debug> flag.
650
+
651
+ For this facet the C<details> flag is the info itself. This info may be a
652
+ string, or it may be a data structure to display. This is one of the few facet
653
+ types that may contain blessed items.
654
+
655
+ =back
656
+
657
+ =head2 LEGACY API
658
+
659
+ =over 4
660
+
661
+ =item $bool = $e->causes_fail
662
+
663
+ Returns true if this event should result in a test failure. In general this
664
+ should be false.
665
+
666
+ =item $bool = $e->increments_count
667
+
668
+ Should be true if this event should result in a test count increment.
669
+
670
+ =item $e->callback($hub)
671
+
672
+ If your event needs to have extra effects on the L<Test2::Hub> you can override
673
+ this method.
674
+
675
+ This is called B<BEFORE> your event is passed to the formatter.
676
+
677
+ =item $num = $e->nested
678
+
679
+ If this event is nested inside of other events, this should be the depth of
680
+ nesting. (This is mainly for subtests)
681
+
682
+ =item $bool = $e->global
683
+
684
+ Set this to true if your event is global, that is ALL threads and processes
685
+ should see it no matter when or where it is generated. This is not a common
686
+ thing to want, it is used by bail-out and skip_all to end testing.
687
+
688
+ =item $code = $e->terminate
689
+
690
+ This is called B<AFTER> your event has been passed to the formatter. This
691
+ should normally return undef, only change this if your event should cause the
692
+ test to exit immediately.
693
+
694
+ If you want this event to cause the test to exit you should return the exit
695
+ code here. Exit code of 0 means exit success, any other integer means exit with
696
+ failure.
697
+
698
+ This is used by L<Test2::Event::Plan> to exit 0 when the plan is
699
+ 'skip_all'. This is also used by L<Test2::Event:Bail> to force the test
700
+ to exit with a failure.
701
+
702
+ This is called after the event has been sent to the formatter in order to
703
+ ensure the event is seen and understood.
704
+
705
+ =item $msg = $e->summary
706
+
707
+ This is intended to be a human readable summary of the event. This should
708
+ ideally only be one line long, but you can use multiple lines if necessary. This
709
+ is intended for human consumption. You do not need to make it easy for machines
710
+ to understand.
711
+
712
+ The default is to simply return the event package name.
713
+
714
+ =item ($count, $directive, $reason) = $e->sets_plan()
715
+
716
+ Check if this event sets the testing plan. It will return an empty list if it
717
+ does not. If it does set the plan it will return a list of 1 to 3 items in
718
+ order: Expected Test Count, Test Directive, Reason for directive.
719
+
720
+ =item $bool = $e->diagnostics
721
+
722
+ True if the event contains diagnostics info. This is useful because a
723
+ non-verbose harness may choose to hide events that are not in this category.
724
+ Some formatters may choose to send these to STDERR instead of STDOUT to ensure
725
+ they are seen.
726
+
727
+ =item $bool = $e->no_display
728
+
729
+ False by default. This will return true on events that should not be displayed
730
+ by formatters.
731
+
732
+ =item $id = $e->in_subtest
733
+
734
+ If the event is inside a subtest this should have the subtest ID.
735
+
736
+ =item $id = $e->subtest_id
737
+
738
+ If the event is a final subtest event, this should contain the subtest ID.
739
+
740
+ =back
741
+
742
+ =head1 THIRD PARTY META-DATA
743
+
744
+ This object consumes L<Test2::Util::ExternalMeta> which provides a consistent
745
+ way for you to attach meta-data to instances of this class. This is useful for
746
+ tools, plugins, and other extensions.
747
+
748
+ =head1 SOURCE
749
+
750
+ The source code repository for Test2 can be found at
751
+ L<https://github.com/Test-More/test-more/>.
752
+
753
+ =head1 MAINTAINERS
754
+
755
+ =over 4
756
+
757
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
758
+
759
+ =back
760
+
761
+ =head1 AUTHORS
762
+
763
+ =over 4
764
+
765
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
766
+
767
+ =back
768
+
769
+ =head1 COPYRIGHT
770
+
771
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
772
+
773
+ This program is free software; you can redistribute it and/or
774
+ modify it under the same terms as Perl itself.
775
+
776
+ See L<https://dev.perl.org/licenses/>
777
+
778
+ =cut
git/usr/share/perl5/core_perl/Test2/EventFacet.pm ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package Test2::EventFacet;
2
+ use strict;
3
+ use warnings;
4
+
5
+ our $VERSION = '1.302210';
6
+
7
+ use Test2::Util::HashBase qw/-details/;
8
+ use Carp qw/croak/;
9
+
10
+ my $SUBLEN = length(__PACKAGE__ . '::');
11
+ sub facet_key {
12
+ my $key = ref($_[0]) || $_[0];
13
+ substr($key, 0, $SUBLEN, '');
14
+ return lc($key);
15
+ }
16
+
17
+ sub is_list { 0 }
18
+
19
+ sub clone {
20
+ my $self = shift;
21
+ my $type = ref($self);
22
+ return bless {%$self, @_}, $type;
23
+ }
24
+
25
+ 1;
26
+
27
+ __END__
28
+
29
+ =pod
30
+
31
+ =encoding UTF-8
32
+
33
+ =head1 NAME
34
+
35
+ Test2::EventFacet - Base class for all event facets.
36
+
37
+ =head1 DESCRIPTION
38
+
39
+ Base class for all event facets.
40
+
41
+ =head1 METHODS
42
+
43
+ =over 4
44
+
45
+ =item $key = $facet_class->facet_key()
46
+
47
+ This will return the key for the facet in the facet data hash.
48
+
49
+ =item $bool = $facet_class->is_list()
50
+
51
+ This will return true if the facet should be in a list instead of a single
52
+ item.
53
+
54
+ =item $clone = $facet->clone()
55
+
56
+ =item $clone = $facet->clone(%replace)
57
+
58
+ This will make a shallow clone of the facet. You may specify fields to override
59
+ as arguments.
60
+
61
+ =back
62
+
63
+ =head1 SOURCE
64
+
65
+ The source code repository for Test2 can be found at
66
+ L<https://github.com/Test-More/test-more/>.
67
+
68
+ =head1 MAINTAINERS
69
+
70
+ =over 4
71
+
72
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
73
+
74
+ =back
75
+
76
+ =head1 AUTHORS
77
+
78
+ =over 4
79
+
80
+ =item Chad Granum E<lt>exodist@cpan.orgE<gt>
81
+
82
+ =back
83
+
84
+ =head1 COPYRIGHT
85
+
86
+ Copyright Chad Granum E<lt>exodist@cpan.orgE<gt>.
87
+
88
+ This program is free software; you can redistribute it and/or
89
+ modify it under the same terms as Perl itself.
90
+
91
+ See L<https://dev.perl.org/licenses/>
92
+
93
+ =cut