001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.bct; 018 019import static java.util.stream.Collectors.*; 020import static org.apache.juneau.commons.utils.Shorts.*; 021import static org.apache.juneau.commons.utils.StringUtils.*; 022import static org.apache.juneau.commons.utils.ThrowableUtils.*; 023import static org.apache.juneau.bct.BctUtils.*; 024import static org.junit.jupiter.api.Assertions.*; 025import static org.junit.jupiter.api.Assertions.assertNotNull; 026 027import java.util.*; 028import java.util.function.*; 029import java.util.stream.*; 030 031import org.apache.juneau.commons.utils.*; 032import org.opentest4j.*; 033 034/** 035 * Comprehensive utility class for Bean-Centric Tests (BCT) and general testing operations. 036 * 037 * <p>This class extends the functionality provided by the JUnit Assertions class, with particular emphasis 038 * on the Bean-Centric Testing (BCT) framework. BCT enables sophisticated assertion patterns for 039 * testing object properties, collections, maps, and complex nested structures with minimal code.</p> 040 * 041 * <h2 class='section'>Bean-Centric Testing (BCT) Framework:</h2> 042 * <p>The BCT framework consists of several key components:</p> 043 * <ul> 044 * <li><b>{@link BeanConverter}:</b> Core interface for object conversion and property access</li> 045 * <li><b>{@link BasicBeanConverter}:</b> Default implementation with extensible type handlers</li> 046 * <li><b>Assertion Methods:</b> High-level testing methods that leverage the converter framework</li> 047 * </ul> 048 * 049 * <h2 class='section'>Primary BCT Assertion Methods:</h2> 050 * <dl> 051 * <dt><b>{@link #assertBean(Object, String, String)}</b></dt> 052 * <dd>Tests object properties with nested syntax support and collection iteration</dd> 053 * 054 * <dt><b>{@link #assertBeans(Collection, String, String...)}</b></dt> 055 * <dd>Tests collections of objects by extracting and comparing specific fields</dd> 056 * 057 * <dt><b>{@link #assertMapped(Object, BiFunction, String, String)}</b></dt> 058 * <dd>Tests custom property access using BiFunction for non-standard objects</dd> 059 * 060 * <dt><b>{@link #assertList(List, Object...)}</b></dt> 061 * <dd>Tests list/collection elements with varargs for expected values</dd> 062 * </dl> 063 * 064 * <h2 class='section'>BCT Advanced Features:</h2> 065 * <ul> 066 * <li><b>Nested Property Syntax:</b> "address{street,city}" for testing nested objects</li> 067 * <li><b>Collection Iteration:</b> "#{address{street,city}}" syntax for testing all elements</li> 068 * <li><b>Universal Size Properties:</b> "length" and "size" work on all collection types</li> 069 * <li><b>Array/List Access:</b> Numeric indices for element-specific testing</li> 070 * <li><b>Method Chaining:</b> Fluent setters can be tested directly</li> 071 * <li><b>Direct Field Access:</b> Public fields accessed without getters</li> 072 * <li><b>Map Key Access:</b> Including special <js>"<null>"</js> syntax for null keys</li> 073 * </ul> 074 * 075 * <h2 class='section'>Converter Extensibility:</h2> 076 * <p>The BCT framework is built on the extensible {@link BasicBeanConverter} which allows:</p> 077 * <ul> 078 * <li><b>Custom Stringifiers:</b> Type-specific string conversion logic</li> 079 * <li><b>Custom Listifiers:</b> Collection-type conversion for iteration</li> 080 * <li><b>Custom Swappers:</b> Object transformation before conversion</li> 081 * <li><b>Custom PropertyExtractors:</b> Property extraction</li> 082 * <li><b>Configurable Settings:</b> Formatting, delimiters, and display options</li> 083 * </ul> 084 * 085 * <h2 class='section'>Usage Examples:</h2> 086 * 087 * <p><b>Basic Property Testing:</b></p> 088 * <p class='bjava'> 089 * <jc>// Test multiple properties</jc> 090 * <jsm>assertBean</jsm>(<jv>user</jv>, <js>"name,age,active"</js>, <js>"John,30,true"</js>); 091 * 092 * <jc>// Test nested properties - user has getAddress() returning Address with getStreet() and getCity()</jc> 093 * <jsm>assertBean</jsm>(<jv>user</jv>, <js>"name,address{street,city}"</js>, <js>"John,{123 Main St,Springfield}"</js>); 094 * </p> 095 * 096 * <p><b>Collection and Array Testing:</b></p> 097 * <p class='bjava'> 098 * <jc>// Test collection size and iterate over all elements - order has getItems() returning List<Product> where Product has getName()</jc> 099 * <jsm>assertBean</jsm>(<jv>order</jv>, <js>"items{length,#{name}}"</js>, <js>"{3,[{Laptop},{Phone},{Tablet}]}"</js>); 100 * 101 * <jc>// Test specific array elements - listOfData is a List<DataObject> where DataObject has getData()</jc> 102 * <jsm>assertBean</jsm>(<jv>listOfData</jv>, <js>"0{data},1{data}"</js>, <js>"{100},{200}"</js>); 103 * </p> 104 * 105 * <p><b>Collection Testing:</b></p> 106 * <p class='bjava'> 107 * <jc>// Test list elements</jc> 108 * <jsm>assertList</jsm>(tags, <js>"red"</js>, <js>"green"</js>, <js>"blue"</js>); 109 * 110 * <jc>// Test map entries using assertBean</jc> 111 * <jsm>assertBean</jsm>(<jv>config</jv>, <js>"timeout,retries"</js>, <js>"30000,3"</js>); 112 * </p> 113 * 114 * <p><b>Custom Property Access:</b></p> 115 * <p class='bjava'> 116 * <jc>// Test with custom accessor function</jc> 117 * <jsm>assertMapped</jsm>(<jv>myObject</jv>, (<jp>obj</jp>, <jp>prop</jp>) -> <jp>obj</jp>.getProperty(<jp>prop</jp>), 118 * <js>"prop1,prop2"</js>, <js>"value1,value2"</js>); 119 * </p> 120 * 121 * <h2 class='section'>Customizing the Default Converter:</h2> 122 * <p>The default bean converter can be customized on a per-thread basis using:</p> 123 * <ul> 124 * <li><b>{@link BctConfiguration#set(BeanConverter)}:</b> Set a custom converter for the current thread</li> 125 * <li><b>{@link BctConfiguration#clear()}:</b> Reset to the system default converter</li> 126 * </ul> 127 * 128 * <p class='bjava'> 129 * <jc>// Example: Set custom converter in @BeforeEach method</jc> 130 * <ja>@BeforeEach</ja> 131 * <jk>void</jk> <jsm>setUp</jsm>() { 132 * <jk>var</jk> <jv>customConverter</jv> = BasicBeanConverter.<jsm>builder</jsm>() 133 * .defaultSettings() 134 * .addStringifier(LocalDate.<jk>class</jk>, <jp>date</jp> -> <jp>date</jp>.format(DateTimeFormatter.<jsf>ISO_LOCAL_DATE</jsf>)) 135 * .addStringifier(MyType.<jk>class</jk>, <jp>obj</jp> -> <jp>obj</jp>.customFormat()) 136 * .build(); 137 * BctAssertions.<jsm>setConverter</jsm>(<jv>customConverter</jv>); 138 * } 139 * 140 * <jc>// All assertions in this test class now use the custom converter</jc> 141 * <ja>@Test</ja> 142 * <jk>void</jk> <jsm>testWithCustomConverter</jsm>() { 143 * <jsm>assertBean</jsm>(<jv>myObject</jv>, <js>"date,property"</js>, <js>"2023-12-01,value"</js>); 144 * } 145 * 146 * <jc>// Clean up in @AfterEach method</jc> 147 * <ja>@AfterEach</ja> 148 * <jk>void</jk> <jsm>tearDown</jsm>() { 149 * BctAssertions.<jsm>resetConverter</jsm>(); 150 * } 151 * </p> 152 * 153 * <p class='bjava'> 154 * <jc>// Example: Per-test method converter override</jc> 155 * <ja>@Test</ja> 156 * <jk>void</jk> <jsm>testSpecificFormat</jsm>() { 157 * <jk>var</jk> <jv>dateConverter</jv> = BasicBeanConverter.<jsm>builder</jsm>() 158 * .defaultSettings() 159 * .addStringifier(LocalDateTime.<jk>class</jk>, <jp>dt</jp> -> <jp>dt</jp>.format(DateTimeFormatter.<jsf>ISO_DATE_TIME</jsf>)) 160 * .build(); 161 * BctAssertions.<jsm>setConverter</jsm>(<jv>dateConverter</jv>); 162 * <jk>try</jk> { 163 * <jsm>assertBean</jsm>(<jv>event</jv>, <js>"timestamp"</js>, <js>"2023-12-01T10:30:00"</js>); 164 * } <jk>finally</jk> { 165 * BctAssertions.<jsm>resetConverter</jsm>(); 166 * } 167 * } 168 * </p> 169 * 170 * <h2 class='section'>Performance and Thread Safety:</h2> 171 * <p>The BCT framework is designed for high performance with:</p> 172 * <ul> 173 * <li><b>Caching:</b> Type-to-handler mappings cached for fast lookup</li> 174 * <li><b>Thread Safety:</b> All operations are thread-safe for concurrent testing</li> 175 * <li><b>Thread-Local Storage:</b> Default converter is stored per-thread, allowing parallel test execution</li> 176 * <li><b>Minimal Allocation:</b> Efficient object reuse and minimal temporary objects</li> 177 * </ul> 178 * 179 * @see BeanConverter 180 * @see BasicBeanConverter 181 * @see BctConfiguration#set(BeanConverter) 182 * @see BctConfiguration#clear() 183 */ 184@SuppressWarnings({ 185 "java:S115", // Constants use UPPER_snakeCase naming convention 186 "java:S1192", // Duplicated literals (argument/property names) read more clearly inline than as constants 187 "java:S5960" // Test-assertion library shipped as main source; JUnit assertions are its intentional purpose 188}) 189public class BctAssertions { 190 191 /** 192 * Sets a custom bean converter for the current thread. 193 * 194 * <p>Thin passthrough to {@link BctConfiguration#set(BeanConverter)}, provided here since every 195 * BCT caller already statically imports {@link BctAssertions}.<jsm>*</jsm> and would otherwise need to 196 * separately reference {@link BctConfiguration} just to override the converter.</p> 197 * 198 * <h4 class='section'>Example:</h4> 199 * <p class='bjava'> 200 * <ja>@BeforeEach</ja> 201 * <jk>void</jk> <jsm>setUp</jsm>() { 202 * BctAssertions.<jsm>setConverter</jsm>(<jv>customConverter</jv>); 203 * } 204 * </p> 205 * 206 * @param converter The bean converter to use for the current thread. Must not be <jk>null</jk>. 207 * @throws IllegalArgumentException If converter is <jk>null</jk>. 208 * @see #resetConverter() 209 * @see BctConfiguration#set(BeanConverter) 210 */ 211 public static void setConverter(BeanConverter converter) { 212 BctConfiguration.set(converter); 213 } 214 215 /** 216 * Resets the bean converter for the current thread back to the system default. 217 * 218 * <p>Thin passthrough to {@link BctConfiguration#clear()}, provided here since every BCT caller 219 * already statically imports {@link BctAssertions}.<jsm>*</jsm> and would otherwise need to 220 * separately reference {@link BctConfiguration} just to reset the converter.</p> 221 * 222 * <h4 class='section'>Example:</h4> 223 * <p class='bjava'> 224 * <ja>@AfterEach</ja> 225 * <jk>void</jk> <jsm>tearDown</jsm>() { 226 * BctAssertions.<jsm>resetConverter</jsm>(); 227 * } 228 * </p> 229 * 230 * @see #setConverter(BeanConverter) 231 * @see BctConfiguration#clear() 232 */ 233 public static void resetConverter() { 234 BctConfiguration.clear(); 235 } 236 237 /** 238 * Asserts that the fields/properties on the specified bean are the specified values after being converted to strings. 239 * 240 * <p>Same as {@link #assertBean(Supplier, Object, String, String)} but without a custom message.</p> 241 * 242 * @param actual The bean object to test. Must not be null. 243 * @param fields Comma-delimited list of property names to test. Supports nested syntax with {}. 244 * @param expected Comma-delimited list of expected values. Must match the order of fields. 245 * @throws AssertionError if the bean is null or any property values don't match expected values 246 * @see #assertBean(Supplier, Object, String, String) 247 */ 248 public static void assertBean(Object actual, String fields, String expected) { 249 assertBean(null, actual, fields, expected); 250 } 251 252 /** 253 * Asserts that the fields/properties on the specified bean are the specified values after being converted to strings. 254 * 255 * <p>This is the primary method for Bean-Centric Tests (BCT), supporting extensive property validation 256 * patterns including nested objects, collections, arrays, method chaining, direct field access, collection iteration 257 * with <js>"#{property}"</js> syntax, and universal <js>"length"</js>/<js>"size"</js> properties for all collection types.</p> 258 * 259 * <p>The method uses the default converter (set via {@link BctConfiguration#set(BeanConverter)}) for object introspection 260 * and value extraction. The converter provides sophisticated property access through the {@link BeanConverter} 261 * interface, supporting multiple fallback mechanisms for accessing object properties and values.</p> 262 * 263 * <h4 class='section'>Basic Usage:</h4> 264 * <p class='bjava'> 265 * <jc>// Test multiple properties</jc> 266 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"prop1,prop2,prop3"</js>, <js>"val1,val2,val3"</js>); 267 * 268 * <jc>// Test single property</jc> 269 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"name"</js>, <js>"John"</js>); 270 * 271 * <jc>// With custom error message</jc> 272 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"name,age"</js>, <js>"John,30"</js>, () -> <js>"User validation failed"</js>); 273 * 274 * <jc>// With formatted message using Shorts.fs() for convenient message suppliers with arguments</jc> 275 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"name,age"</js>, <js>"John,30"</js>, <jsm>fs</jsm>(<js>"User %s validation failed"</js>, <js>"John"</js>)); 276 * </p> 277 * 278 * <h4 class='section'>Nested Property Testing:</h4> 279 * <p class='bjava'> 280 * <jc>// Test nested bean properties</jc> 281 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"name,address{street,city,state}"</js>, <js>"John,{123 Main St,Springfield,IL}"</js>); 282 * 283 * <jc>// Test arbitrarily deep nesting</jc> 284 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"name,person{address{geo{lat,lon}}}"</js>, <js>"John,{{{40.7,-74.0}}}"</js>); 285 * </p> 286 * 287 * <h4 class='section'>Array, List, and Stream Testing:</h4> 288 * <p class='bjava'> 289 * <jc>// Test array/list elements by index - items is a String[] or List<String></jc> 290 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"items{0,1,2}"</js>, <js>"{item1,item2,item3}"</js>); 291 * 292 * <jc>// Test nested properties within array elements - orders is a List<Order> where Order has getId() and getTotal()</jc> 293 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"orders{0{id,total}}"</js>, <js>"{{123,99.95}}"</js>); 294 * 295 * <jc>// Test array length property - items can be any array or collection type</jc> 296 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"items{length}"</js>, <js>"{5}"</js>); 297 * 298 * <jc>// Works with any iterable type including Streams - userStream returns a Stream<User> where User has getName()</jc> 299 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"userStream{#{name}}"</js>, <js>"[{Alice},{Bob}]"</js>); 300 * </p> 301 * 302 * <h4 class='section'>Collection Iteration Syntax:</h4> 303 * <p class='bjava'> 304 * <jc>// Test properties across ALL elements in a collection using #{...} syntax - userList is a List<User> where User has getName()</jc> 305 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"userList{#{name}}"</js>, <js>"[{John},{Jane},{Bob}]"</js>); 306 * 307 * <jc>// Test multiple properties from each element - orderList is a List<Order> where Order has getId() and getStatus()</jc> 308 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"orderList{#{id,status}}"</js>, <js>"[{123,ACTIVE},{124,PENDING}]"</js>); 309 * 310 * <jc>// Works with nested properties within each element - customers is a List<Customer> where Customer has getAddress() returning Address with getCity()</jc> 311 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"customers{#{address{city}}}"</js>, <js>"[{{New York}},{{Los Angeles}}]"</js>); 312 * 313 * <jc>// Works with arrays and any iterable collection type (including Streams)</jc> 314 * <jsm>assertBean</jsm>(<jv>config</jv>, <js>"itemArray{#{type}}"</js>, <js>"[{String},{Integer},{Boolean}]"</js>); 315 * <jsm>assertBean</jsm>(<jv>data</jv>, <js>"statusSet{#{name}}"</js>, <js>"[{ACTIVE},{PENDING},{CANCELLED}]"</js>); 316 * <jsm>assertBean</jsm>(<jv>processor</jv>, <js>"dataStream{#{value}}"</js>, <js>"[{A},{B},{C}]"</js>); 317 * </p> 318 * 319 * <h4 class='section'>Universal Collection Size Properties:</h4> 320 * <p class='bjava'> 321 * <jc>// Both 'length' and 'size' work universally across all collection types</jc> 322 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myArray{length}"</js>, <js>"{5}"</js>); <jc>// Arrays</jc> 323 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myArray{size}"</js>, <js>"{5}"</js>); <jc>// Also works for arrays</jc> 324 * 325 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myList{size}"</js>, <js>"{3}"</js>); <jc>// Collections</jc> 326 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myList{length}"</js>, <js>"{3}"</js>); <jc>// Also works for collections</jc> 327 * 328 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myMap{size}"</js>, <js>"{7}"</js>); <jc>// Maps</jc> 329 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"myMap{length}"</js>, <js>"{7}"</js>); <jc>// Also works for maps</jc> 330 * </p> 331 * 332 * <h4 class='section'>Class Name Testing:</h4> 333 * <p class='bjava'> 334 * <jc>// Test class properties (prefer simple names for maintainability)</jc> 335 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"obj{class{simpleName}}"</js>, <js>"{{MyClass}}"</js>); 336 * 337 * <jc>// Test full class names when needed</jc> 338 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"obj{class{name}}"</js>, <js>"{{com.example.MyClass}}"</js>); 339 * </p> 340 * 341 * <h4 class='section'>Method Chaining Support:</h4> 342 * <p class='bjava'> 343 * <jc>// Test fluent setter chains (returns same object)</jc> 344 * <jsm>assertBean</jsm>( 345 * <jv>item</jv>.setType(<js>"foo"</js>).setFormat(<js>"bar"</js>).setDefault(<js>"baz"</js>), 346 * <js>"type,format,default"</js>, 347 * <js>"foo,bar,baz"</js> 348 * ); 349 * </p> 350 * 351 * <h4 class='section'>Advanced Collection Analysis:</h4> 352 * <p class='bjava'> 353 * <jc>// Combine size/length, metadata, and content iteration in single assertions - users is a List<User></jc> 354 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"users{length,class{simpleName},#{name}}"</js>, 355 * <js>"{3,{ArrayList},[{John},{Jane},{Bob}]}"</js>); 356 * 357 * <jc>// Comprehensive collection validation with multiple iteration patterns - items is a List<Product> where Product has getName() and getPrice()</jc> 358 * <jsm>assertBean</jsm>(<jv>order</jv>, <js>"items{size,#{name},#{price}}"</js>, 359 * <js>"{3,[{Laptop},{Phone},{Tablet}],[{999.99},{599.99},{399.99}]}"</js>); 360 * 361 * <jc>// Perfect for validation testing - verify error count and details; errors is a List<ValidationError> where ValidationError has getField() and getCode()</jc> 362 * <jsm>assertBean</jsm>(<jv>result</jv>, <js>"errors{length,#{field},#{code}}"</js>, 363 * <js>"{2,[{email},{password}],[{E001},{E002}]}"</js>); 364 * 365 * <jc>// Mixed collection types with consistent syntax - results and metadata are different collection types</jc> 366 * <jsm>assertBean</jsm>(<jv>response</jv>, <js>"results{size},metadata{length}"</js>, <js>"{25},{4}"</js>); 367 * </p> 368 * 369 * <h4 class='section'>Direct Field Access:</h4> 370 * <p class='bjava'> 371 * <jc>// Test public fields directly (no getters required)</jc> 372 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"f1,f2,f3"</js>, <js>"val1,val2,val3"</js>); 373 * 374 * <jc>// Test field properties with chaining</jc> 375 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"f1{length},f2{class{simpleName}}"</js>, <js>"{5},{{String}}"</js>); 376 * </p> 377 * 378 * <h4 class='section'>Map Testing:</h4> 379 * <p class='bjava'> 380 * <jc>// Test map values by key</jc> 381 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"configMap{timeout,retries}"</js>, <js>"{30000,3}"</js>); 382 * 383 * <jc>// Test map size</jc> 384 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"settings{size}"</js>, <js>"{5}"</js>); 385 * 386 * <jc>// Test null keys using special <null> syntax</jc> 387 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"mapWithNullKey{<null>}"</js>, <js>"{nullKeyValue}"</js>); 388 * </p> 389 * 390 * <h4 class='section'>Collection and Boolean Values:</h4> 391 * <p class='bjava'> 392 * <jc>// Test boolean values</jc> 393 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"enabled,visible"</js>, <js>"true,false"</js>); 394 * 395 * <jc>// Test enum collections</jc> 396 * <jsm>assertBean</jsm>(<jv>myBean</jv>, <js>"statuses"</js>, <js>"[ACTIVE,PENDING]"</js>); 397 * </p> 398 * 399 * <h4 class='section'>Value Syntax Rules:</h4> 400 * <ul> 401 * <li><b>Simple values:</b> <js>"value"</js> for direct property values</li> 402 * <li><b>Nested values:</b> <js>"{value}"</js> for single-level nested properties</li> 403 * <li><b>Deep nested values:</b> <js>"{{value}}"</js>, <js>"{{{value}}}"</js> for multiple nesting levels</li> 404 * <li><b>Array/Collection values:</b> <js>"[item1,item2]"</js> for collections</li> 405 * <li><b>Collection iteration:</b> <js>"#{property}"</js> iterates over ALL collection elements, returns <js>"[{val1},{val2}]"</js></li> 406 * <li><b>Universal size properties:</b> <js>"length"</js> and <js>"size"</js> work on arrays, collections, and maps</li> 407 * <li><b>Boolean values:</b> <js>"true"</js>, <js>"false"</js></li> 408 * <li><b>Null values:</b> <js>"null"</js></li> 409 * </ul> 410 * 411 * <h4 class='section'>Property Access Priority:</h4> 412 * <ol> 413 * <li><b>Collection/Array access:</b> Numeric indices for arrays/lists (e.g., <js>"0"</js>, <js>"1"</js>)</li> 414 * <li><b>Universal size properties:</b> <js>"length"</js> and <js>"size"</js> for arrays, collections, and maps</li> 415 * <li><b>Map key access:</b> Direct key lookup for Map objects (including <js>"<null>"</js> for null keys)</li> 416 * <li><b>is{Property}()</b> methods (for boolean properties)</li> 417 * <li><b>get{Property}()</b> methods</li> 418 * <li><b>Public fields</b> (direct field access)</li> 419 * </ol> 420 * 421 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 422 * Use {@link Shorts#fs(String, Object...) Shorts.fs()} to conveniently 423 * create message suppliers with format arguments (e.g., <code>fs("User %s validation failed", userName)</code>). 424 * @param actual The bean object to test. Must not be null. 425 * @param fields Comma-delimited list of property names to test. Supports nested syntax with {}. 426 * @param expected Comma-delimited list of expected values. Must match the order of fields. 427 * @throws AssertionError if the bean is null or any property values don't match expected values 428 * @see BeanConverter 429 * @see BasicBeanConverter 430 * @see BctConfiguration#set(BeanConverter) 431 * @see Shorts#fs(String, Object...) 432 */ 433 public static void assertBean(Supplier<String> message, Object actual, String fields, String expected) { 434 assertNotNull(actual, "Actual was null."); 435 reqnn("fields", fields); 436 reqnn("expected", expected); 437 var converter = BctConfiguration.getConverter(); 438 assertEquals(expected, tokenize(fields).stream().map(x -> converter.getNested(actual, x)).collect(joining(",")), composeMessage(message, "Bean assertion failed.")); 439 } 440 441 /** 442 * Asserts that multiple beans in a collection have the expected property values. 443 * 444 * <p>This method validates that each bean in a collection has the specified property values, 445 * using the same property access logic as {@link #assertBean(Object, String, String)}. 446 * It's perfect for testing collections of similar objects or validation results.</p> 447 * 448 * <h4 class='section'>Basic Usage:</h4> 449 * <p class='bjava'> 450 * <jc>// Test list of user beans</jc> 451 * <jsm>assertBeans</jsm>(<jv>userList</jv>, <js>"name,age"</js>, 452 * <js>"John,25"</js>, <js>"Jane,30"</js>, <js>"Bob,35"</js>); 453 * </p> 454 * 455 * <h4 class='section'>Complex Property Testing:</h4> 456 * <p class='bjava'> 457 * <jc>// Test nested properties across multiple beans - orderList is a List<Order> where Order has getId() and getCustomer() returning Customer with getName() and getEmail()</jc> 458 * <jsm>assertBeans</jsm>(<jv>orderList</jv>, <js>"id,customer{name,email}"</js>, 459 * <js>"1,{John,john@example.com}"</js>, 460 * <js>"2,{Jane,jane@example.com}"</js>); 461 * 462 * <jc>// Test collection properties within beans - cartList is a List<ShoppingCart> where ShoppingCart has getItems() returning List<Product> and getTotal()</jc> 463 * <jsm>assertBeans</jsm>(<jv>cartList</jv>, <js>"items{0{name}},total"</js>, 464 * <js>"{{Laptop}},999.99"</js>, 465 * <js>"{{Phone}},599.99"</js>); 466 * </p> 467 * 468 * <h4 class='section'>Validation Testing:</h4> 469 * <p class='bjava'> 470 * <jc>// Test validation results</jc> 471 * <jsm>assertBeans</jsm>(<jv>validationErrors</jv>, <js>"field,message,code"</js>, 472 * <js>"email,Invalid email format,E001"</js>, 473 * <js>"age,Must be 18 or older,E002"</js>); 474 * </p> 475 * 476 * <h4 class='section'>Collection Iteration Testing:</h4> 477 * <p class='bjava'> 478 * <jc>// Test collection iteration within beans (#{...} syntax)</jc> 479 * <jsm>assertBeans</jsm>(<jv>departmentList</jv>, <js>"name,employees{#{name}}"</js>, 480 * <js>"Engineering,[{Alice},{Bob},{Charlie}]"</js>, 481 * <js>"Marketing,[{David},{Eve}]"</js>); 482 * </p> 483 * 484 * <h4 class='section'>Parser Result Testing:</h4> 485 * <p class='bjava'> 486 * <jc>// Test parsed object collections</jc> 487 * <jk>var</jk> <jv>parsed</jv> = JsonParser.<jsf>DEFAULT</jsf>.read(<jv>jsonArray</jv>, MyBean[].class); 488 * <jsm>assertBeans</jsm>(<jsm>l</jsm>(<jv>parsed</jv>), <js>"prop1,prop2"</js>, 489 * <js>"val1,val2"</js>, <js>"val3,val4"</js>); 490 * </p> 491 * 492 * @param actual The collection of beans to check. Must not be null. 493 * @param fields A comma-delimited list of bean property names (supports nested syntax). 494 * @param expected Array of expected value strings, one per bean. Each string contains comma-delimited values matching the fields. 495 * @throws AssertionError if the collection size doesn't match values array length or if any bean properties don't match 496 * @see #assertBean(Object, String, String) 497 */ 498 public static void assertBeans(Object actual, String fields, String...expected) { 499 assertBeans(null, actual, fields, expected); 500 } 501 502 /** 503 * Asserts that multiple beans in a collection have the expected property values. 504 * 505 * <p>Same as {@link #assertBeans(Object, String, String...)} but with a custom error message.</p> 506 * 507 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 508 * @param actual The collection of beans to check. Must not be null. 509 * @param fields A comma-delimited list of bean property names (supports nested syntax). 510 * @param expected Array of expected value strings, one per bean. Each string contains comma-delimited values matching the fields. 511 * @throws AssertionError if the collection size doesn't match values array length or if any bean properties don't match 512 * @see #assertBean(Object, String, String) 513 */ 514 public static void assertBeans(Supplier<String> message, Object actual, String fields, String...expected) { 515 assertNotNull(actual, "Value was null."); 516 reqnn("fields", fields); 517 reqnn("expected", expected); 518 519 var converter = BctConfiguration.getConverter(); 520 var tokens = tokenize(fields); 521 var errors = new ArrayList<AssertionFailedError>(); 522 List<Object> actualList = converter.listify(actual); 523 524 if (neq(expected.length, actualList.size())) { 525 errors.add(assertEqualsFailed(expected.length, actualList.size(), composeMessage(message, "Wrong number of beans."))); 526 } else { 527 for (var i = 0; i < actualList.size(); i++) { 528 var i2 = i; 529 var e = converter.stringify(expected[i]); 530 var a = tokens.stream().map(x -> converter.getNested(actualList.get(i2), x)).collect(joining(",")); 531 if (neq(e, a)) { 532 errors.add(assertEqualsFailed(e, a, composeMessage(message, "Bean at row <%s> did not match.", i))); 533 } 534 } 535 } 536 537 if (errors.isEmpty()) 538 return; 539 540 var actualStrings = actualList.stream().map(o -> tokens.stream().map(x -> converter.getNested(o, x)).collect(joining(","))).toList(); 541 542 throw assertEqualsFailed(Stream.of(expected).map(StringUtils::escapeForJava).collect(joining("\", \"", "\"", "\"")), 543 actualStrings.stream().map(StringUtils::escapeForJava).collect(joining("\", \"", "\"", "\"")), 544 composeMessage(message, "%s bean assertions failed:\n%s", errors.size(), errors.stream().map(x -> x.getMessage()).collect(joining("\n")))); 545 } 546 547 /** 548 * Asserts that the string representation of an object contains the expected substring. 549 * 550 * <p>Same as {@link #assertContains(Supplier, String, Object)} but without a custom message.</p> 551 * 552 * @param expected The substring that must be present in the actual object's string representation 553 * @param actual The object to test. Must not be null. 554 * @throws AssertionError if the actual object is null or its string representation doesn't contain the expected substring 555 * @see #assertContains(Supplier, String, Object) 556 */ 557 public static void assertContains(String expected, Object actual) { 558 assertContains(null, expected, actual); 559 } 560 561 /** 562 * Asserts that the string representation of an object contains the expected substring. 563 * 564 * <p>This method converts the actual object to its string representation using the current 565 * {@link BeanConverter} and then checks if it contains the expected substring. This is useful 566 * for testing partial content matches without requiring exact string equality.</p> 567 * 568 * <h4 class='section'>Usage Examples:</h4> 569 * <p class='bjava'> 570 * <jc>// Test that error message contains key information</jc> 571 * <jsm>assertContains</jsm>(<js>"FileNotFoundException"</js>, <jv>exception</jv>); 572 * 573 * <jc>// Test that object string representation contains expected data</jc> 574 * <jsm>assertContains</jsm>(<js>"status=ACTIVE"</js>, <jv>user</jv>); 575 * 576 * <jc>// Test partial JSON/XML content</jc> 577 * <jsm>assertContains</jsm>(<js>"\"name\":\"John\""</js>, <jv>jsonResponse</jv>); 578 * </p> 579 * 580 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 581 * @param expected The substring that must be present in the actual object's string representation 582 * @param actual The object to test. Must not be null. 583 * @throws AssertionError if the actual object is null or its string representation doesn't contain the expected substring 584 * @see #assertContainsAll(Object, String...) for multiple substring assertions 585 * @see #assertString(String, Object) for exact string matching 586 */ 587 public static void assertContains(Supplier<String> message, String expected, Object actual) { 588 reqnn("expected", expected); 589 reqnn("actual", actual); 590 assertNotNull(actual, "Value was null."); 591 592 var a = BctConfiguration.getConverter().stringify(actual); 593 assertTrue(a.contains(expected), composeMessage(message, "String did not contain expected substring. ==> expected: <%s> but was: <%s>", expected, a)); 594 } 595 596 /** 597 * Asserts that the string representation of an object does not contain the specified substring. 598 * 599 * <p>Same as {@link #assertNotContains(Supplier, String, Object)} but without a custom message.</p> 600 * 601 * @param unexpected The substring that must not be present in the actual object's string representation 602 * @param actual The object to test. Must not be null. 603 * @throws AssertionError if the actual object is null or its string representation contains the substring 604 * @see #assertNotContains(Supplier, String, Object) 605 */ 606 public static void assertNotContains(String unexpected, Object actual) { 607 assertNotContains(null, unexpected, actual); 608 } 609 610 /** 611 * Asserts that the string representation of an object does not contain the specified substring. 612 * 613 * <p>This is the negation of {@link #assertContains(Supplier, String, Object)}: the actual object is 614 * converted to its string representation using the current {@link BeanConverter} and must not contain 615 * the substring.</p> 616 * 617 * <h4 class='section'>Usage Examples:</h4> 618 * <p class='bjava'> 619 * <jc>// Test that a rendered page does not leak a value</jc> 620 * <jsm>assertNotContains</jsm>(<js>"password"</js>, <jv>html</jv>); 621 * </p> 622 * 623 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 624 * @param unexpected The substring that must not be present in the actual object's string representation 625 * @param actual The object to test. Must not be null. 626 * @throws AssertionError if the actual object is null or its string representation contains the substring 627 * @see #assertContains(Supplier, String, Object) 628 */ 629 public static void assertNotContains(Supplier<String> message, String unexpected, Object actual) { 630 reqnn("unexpected", unexpected); 631 reqnn("actual", actual); 632 assertNotNull(actual, "Value was null."); 633 634 var a = BctConfiguration.getConverter().stringify(actual); 635 assertFalse(a.contains(unexpected), composeMessage(message, "String contained unexpected substring. ==> unexpected: <%s> but was: <%s>", unexpected, a)); 636 } 637 638 /** 639 * Asserts that the string representation of an object contains all specified substrings. 640 * 641 * <p>Same as {@link #assertContainsAll(Supplier, Object, String...)} but without a custom message.</p> 642 * 643 * @param actual The object to test. Must not be null. 644 * @param expected Multiple substrings that must all be present in the actual object's string representation 645 * @throws AssertionError if the actual object is null or its string representation doesn't contain all expected substrings 646 * @see #assertContainsAll(Supplier, Object, String...) 647 */ 648 public static void assertContainsAll(Object actual, String...expected) { 649 assertContainsAll(null, actual, expected); 650 } 651 652 /** 653 * Asserts that the string representation of an object contains all specified substrings. 654 * 655 * <p>This method is similar to {@link #assertContains(String, Object)} but tests for multiple 656 * required substrings. All provided substrings must be present in the actual object's string 657 * representation for the assertion to pass.</p> 658 * 659 * <h4 class='section'>Usage Examples:</h4> 660 * <p class='bjava'> 661 * <jc>// Test that error contains multiple pieces of information</jc> 662 * <jsm>assertContainsAll</jsm>(<jv>exception</jv>, <js>"FileNotFoundException"</js>, <js>"config.xml"</js>, <js>"/etc"</js>); 663 * 664 * <jc>// Test that user object contains expected fields</jc> 665 * <jsm>assertContainsAll</jsm>(<jv>user</jv>, <js>"name=John"</js>, <js>"age=30"</js>, <js>"status=ACTIVE"</js>); 666 * 667 * <jc>// Test log output contains all required entries</jc> 668 * <jsm>assertContainsAll</jsm>(<jv>logOutput</jv>, <js>"INFO"</js>, <js>"Started"</js>, <js>"Successfully"</js>); 669 * </p> 670 * 671 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 672 * @param actual The object to test. Must not be null. 673 * @param expected Multiple substrings that must all be present in the actual object's string representation 674 * @throws AssertionError if the actual object is null or its string representation doesn't contain all expected substrings 675 * @see #assertContains(String, Object) for single substring assertions 676 */ 677 public static void assertContainsAll(Supplier<String> message, Object actual, String...expected) { 678 reqnn("expected", expected); 679 assertNotNull(actual, "Value was null."); 680 681 var a = BctConfiguration.getConverter().stringify(actual); 682 var errors = Stream.of(expected) 683 .filter(e -> ! a.contains(e)) 684 .map(e -> assertEqualsFailed(true, false, composeMessage(message, "String did not contain expected substring. ==> expected: <%s> but was: <%s>", e, a))) 685 .toList(); 686 687 if (errors.isEmpty()) 688 return; 689 690 if (errors.size() == 1) 691 throw errors.get(0); 692 693 var missingSubstrings = Stream.of(expected).filter(e -> ! a.contains(e)).toList(); 694 695 throw assertEqualsFailed(missingSubstrings.stream().map(StringUtils::escapeForJava).collect(joining("\", \"", "\"", "\"")), escapeForJava(a), 696 composeMessage(message, "%s substring assertions failed:\n%s", errors.size(), errors.stream().map(x -> x.getMessage()).collect(joining("\n")))); 697 } 698 699 /** 700 * Asserts that a collection-like object, Optional, Value, String, or array is not null and empty. 701 * 702 * <p>Same as {@link #assertEmpty(Supplier, Object)} but without a custom message.</p> 703 * 704 * @param value The object to test. Must not be null. 705 * @throws AssertionError if the object is null or not empty 706 * @see #assertEmpty(Supplier, Object) 707 */ 708 public static void assertEmpty(Object value) { 709 assertEmpty(null, value); 710 } 711 712 /** 713 * Asserts that a collection-like object, Optional, Value, String, or array is not null and empty. 714 * 715 * <p>This method validates that the provided object is empty according to its type:</p> 716 * <ul> 717 * <li><b>String:</b> Must have length 0</li> 718 * <li><b>Optional:</b> Must be empty (not present)</li> 719 * <li><b>Value:</b> Must be empty (value is null)</li> 720 * <li><b>Map:</b> Must have no entries</li> 721 * <li><b>Collection:</b> Must have no elements</li> 722 * <li><b>Array:</b> Must have length 0</li> 723 * <li><b>Other objects:</b> Must be convertible to an empty List via {@link BeanConverter#listify(Object)}</li> 724 * </ul> 725 * 726 * <h4 class='section'>Supported Types:</h4> 727 * <p>Any object that can be converted to a List, including:</p> 728 * <ul> 729 * <li>Collections (List, Set, Queue, etc.)</li> 730 * <li>Arrays (primitive and object arrays)</li> 731 * <li>Iterables, Iterators, Streams</li> 732 * <li>Maps (converted to list of entries)</li> 733 * <li>Optional objects</li> 734 * </ul> 735 * 736 * <h4 class='section'>Usage Examples:</h4> 737 * <p class='bjava'> 738 * <jc>// Test empty collections</jc> 739 * <jsm>assertEmpty</jsm>(Collections.<jsm>emptyList</jsm>()); 740 * <jsm>assertEmpty</jsm>(<jk>new</jk> ArrayList<>()); 741 * 742 * <jc>// Test empty arrays</jc> 743 * <jsm>assertEmpty</jsm>(<jk>new</jk> String[0]); 744 * 745 * <jc>// Test empty Optional</jc> 746 * <jsm>assertEmpty</jsm>(Optional.<jsm>empty</jsm>()); 747 * 748 * <jc>// Test empty Map</jc> 749 * <jsm>assertEmpty</jsm>(<jk>new</jk> HashMap<>()); 750 * </p> 751 * 752 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 753 * @param value The object to test. Must not be null. 754 * @throws AssertionError if the object is null or not empty 755 * @see #assertNotEmpty(Object) for testing non-empty collections 756 * @see #assertSize(int, Object) for testing specific sizes 757 */ 758 public static void assertEmpty(Supplier<String> message, Object value) { 759 assertNotNull(value, "Value was null."); 760 var size = BctConfiguration.getConverter().size(value); 761 assertEquals(0, size, composeMessage(message, "Value was not empty. Size=<%s>", size)); 762 } 763 764 /** 765 * Asserts that a List or List-like object contains the expected values using flexible comparison logic. 766 * 767 * <p>Same as {@link #assertList(Supplier, Object, Object...)} but without a custom message.</p> 768 * 769 * @param actual The List to test. Must not be null. 770 * @param expected Multiple arguments of expected values. 771 * Can be Strings (readable format comparison), Predicates (functional testing), or Objects (direct equality). 772 * @throws IllegalArgumentException if actual is null 773 * @throws AssertionError if the List size or contents don't match expected values 774 * @see #assertList(Supplier, Object, Object...) 775 */ 776 public static void assertList(Object actual, Object...expected) { 777 reqnn("actual", actual); 778 assertList(null, actual, expected); 779 } 780 781 /** 782 * Asserts that a List or List-like object contains the expected values using flexible comparison logic. 783 * 784 * <h4 class='section'>Testing Non-List Collections:</h4> 785 * <p class='bjava'> 786 * <jc>// Test a Set using l() conversion</jc> 787 * Set<String> <jv>mySet</jv> = <jk>new</jk> TreeSet<>(Arrays.<jsm>asList</jsm>(<js>"a"</js>, <js>"b"</js>, <js>"c"</js>)); 788 * <jsm>assertList</jsm>(<jsm>l</jsm>(<jv>mySet</jv>), <js>"a"</js>, <js>"b"</js>, <js>"c"</js>); 789 * 790 * <jc>// Test an array using l() conversion</jc> 791 * String[] <jv>myArray</jv> = {<js>"x"</js>, <js>"y"</js>, <js>"z"</js>}; 792 * <jsm>assertList</jsm>(<jsm>l</jsm>(<jv>myArray</jv>), <js>"x"</js>, <js>"y"</js>, <js>"z"</js>); 793 * 794 * <jc>// Test a Stream using l() conversion</jc> 795 * Stream<String> <jv>myStream</jv> = Stream.<jsm>of</jsm>(<js>"foo"</js>, <js>"bar"</js>); 796 * <jsm>assertList</jsm>(<jsm>l</jsm>(<jv>myStream</jv>), <js>"foo"</js>, <js>"bar"</js>); 797 * </p> 798 * 799 * <h4 class='section'>Comparison Modes:</h4> 800 * <p>The method supports three different ways to compare expected vs actual values:</p> 801 * 802 * <h5 class='section'>1. String Comparison (Readable Format):</h5> 803 * <p class='bjava'> 804 * <jc>// Elements are converted to strings using the bean converter and compared as strings</jc> 805 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(1, 2, 3), <js>"1"</js>, <js>"2"</js>, <js>"3"</js>); 806 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(<js>"a"</js>, <js>"b"</js>), <js>"a"</js>, <js>"b"</js>); 807 * </p> 808 * 809 * <h5 class='section'>2. Predicate Testing (Functional Validation):</h5> 810 * <p class='bjava'> 811 * <jc>// Use Predicate<T> for functional testing</jc> 812 * Predicate<Integer> <jv>greaterThanOne</jv> = <jv>x</jv> -> <jv>x</jv> > 1; 813 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(2, 3, 4), <jv>greaterThanOne</jv>, <jv>greaterThanOne</jv>, <jv>greaterThanOne</jv>); 814 * 815 * <jc>// Mix predicates with other comparison types</jc> 816 * Predicate<String> <jv>startsWithA</jv> = <jv>s</jv> -> <jv>s</jv>.startsWith(<js>"a"</js>); 817 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(<js>"apple"</js>, <js>"banana"</js>), <jv>startsWithA</jv>, <js>"banana"</js>); 818 * </p> 819 * 820 * <h5 class='section'>3. Object Equality (Direct Comparison):</h5> 821 * <p class='bjava'> 822 * <jc>// Non-String, non-Predicate objects use <jsm>Objects.equals</jsm>() comparison</jc> 823 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(1, 2, 3), 1, 2, 3); <jc>// Integer objects</jc> 824 * <jsm>assertList</jsm>(List.<jsm>of</jsm>(<jv>myBean1</jv>, <jv>myBean2</jv>), <jv>myBean1</jv>, <jv>myBean2</jv>); <jc>// Custom objects</jc> 825 * </p> 826 * 827 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 828 * @param actual The List to test. Must not be null. 829 * @param expected Multiple arguments of expected values. 830 * Can be Strings (readable format comparison), Predicates (functional testing), or Objects (direct equality). 831 * @throws AssertionError if the List size or contents don't match expected values 832 */ 833 @SuppressWarnings({ 834 "java:S3776", // Cognitive complexity acceptable for this specific logic 835 "unchecked" // Type erasure requires unchecked casts 836 }) 837 public static void assertList(Supplier<String> message, Object actual, Object...expected) { 838 reqnn("expected", expected); 839 reqnn("actual", actual); 840 841 var converter = BctConfiguration.getConverter(); 842 List<Object> list = converter.listify(actual); 843 var errors = new ArrayList<AssertionFailedError>(); 844 845 if (neq(expected.length, list.size())) { 846 errors.add(assertEqualsFailed(expected.length, list.size(), composeMessage(message, "Wrong list length."))); 847 } else { 848 for (var i = 0; i < expected.length; i++) { 849 var x = list.get(i); 850 var e = expected[i]; 851 if (e instanceof String e2) { 852 if (neq(e2, converter.stringify(x))) { 853 errors.add(assertEqualsFailed(e2, converter.stringify(x), composeMessage(message, "Element at index %s did not match.", i))); 854 } 855 } else if (e instanceof Predicate<?> p) { 856 Predicate<Object> e2 = (Predicate<Object>) p; 857 if (! e2.test(x)) { 858 errors.add(new AssertionFailedError(composeMessage(message, "Element at index %s did not pass predicate. ==> actual: <%s>", i, converter.stringify(x)).get())); 859 } 860 } else { 861 if (neq(e, x)) { 862 errors.add(assertEqualsFailed(e, x, composeMessage(message, "Element at index %s did not match. ==> expected: <%s(%s)> but was: <%s(%s)>", i, e, cns(e), x, cns(x)))); 863 } 864 } 865 } 866 } 867 868 if (errors.isEmpty()) 869 return; 870 871 var actualStrings = list.stream().map(converter::stringify).toList(); 872 873 if (errors.size() == 1) 874 throw errors.get(0); 875 876 throw assertEqualsFailed(Stream.of(expected).map(converter::stringify).map(StringUtils::escapeForJava).collect(joining("\", \"", "[\"", "\"]")), 877 actualStrings.stream().map(StringUtils::escapeForJava).collect(joining("\", \"", "[\"", "\"]")), 878 composeMessage(message, "%s list assertions failed:\n%s", errors.size(), errors.stream().map(x -> x.getMessage()).collect(joining("\n")))); 879 } 880 881 /** 882 * Asserts that a Map contains the expected key/value pairs using flexible comparison logic. 883 * 884 * <p>Same as {@link #assertMap(Supplier, Map, Object...)} but without a custom message.</p> 885 * 886 * @param actual The Map to test. Must not be null. 887 * @param expected Multiple arguments of expected map entries. 888 * Can be Strings (readable format comparison), Predicates (functional testing), or Objects (direct equality). 889 * @throws AssertionError if the Map size or contents don't match expected values 890 * @see #assertMap(Supplier, Map, Object...) 891 */ 892 public static void assertMap(Map<?,?> actual, Object...expected) { 893 assertMap(null, actual, expected); 894 } 895 896 /** 897 * Asserts that a Map contains the expected key/value pairs using flexible comparison logic. 898 * 899 * <h4 class='section'>Map Entry Serialization:</h4> 900 * <p>Map entries are serialized to strings as key/value pairs in the format <js>"key=value"</js>. 901 * Nested maps and collections are supported with appropriate formatting.</p> 902 * 903 * <h4 class='section'>Testing Nested Maps and Collections:</h4> 904 * <p class='bjava'> 905 * <jc>// Test simple map entries</jc> 906 * Map<String,String> <jv>simpleMap</jv> = Map.<jsm>of</jsm>(<js>"a"</js>, <js>"1"</js>, <js>"b"</js>, <js>"2"</js>); 907 * <jsm>assertMap</jsm>(<jv>simpleMap</jv>, <js>"a=1"</js>, <js>"b=2"</js>); 908 * 909 * <jc>// Test nested maps</jc> 910 * Map<String,Map<String,Integer>> <jv>nestedMap</jv> = Map.<jsm>of</jsm>(<js>"a"</js>, Map.<jsm>of</jsm>(<js>"b"</js>, 1)); 911 * <jsm>assertMap</jsm>(<jv>nestedMap</jv>, <js>"a={b=1}"</js>); 912 * 913 * <jc>// Test maps with arrays/collections</jc> 914 * Map<String,Map<String,Integer[]>> <jv>mapWithArrays</jv> = Map.<jsm>of</jsm>(<js>"a"</js>, Map.<jsm>of</jsm>(<js>"b"</js>, <jk>new</jk> Integer[]{1,2})); 915 * <jsm>assertMap</jsm>(<jv>mapWithArrays</jv>, <js>"a={b=[1,2]}"</js>); 916 * </p> 917 * 918 * <h4 class='section'>Comparison Modes:</h4> 919 * <p>The method supports the same comparison modes as {@link #assertList(Object, Object...)}:</p> 920 * 921 * <h5 class='section'>1. String Comparison (Readable Format):</h5> 922 * <p class='bjava'> 923 * <jc>// Map entries are converted to strings and compared as strings</jc> 924 * <jsm>assertMap</jsm>(Map.<jsm>of</jsm>(<js>"key1"</js>, <js>"value1"</js>), <js>"key1=value1"</js>); 925 * <jsm>assertMap</jsm>(Map.<jsm>of</jsm>(<js>"count"</js>, 42), <js>"count=42"</js>); 926 * </p> 927 * 928 * <h5 class='section'>2. Predicate Testing (Functional Validation):</h5> 929 * <p class='bjava'> 930 * <jc>// Use Predicate<Map.Entry<K,V>> for functional testing</jc> 931 * Predicate<Map.Entry<String,Integer>> <jv>valueGreaterThanTen</jv> = <jv>entry</jv> -> <jv>entry</jv>.getValue() > 10; 932 * <jsm>assertMap</jsm>(Map.<jsm>of</jsm>(<js>"count"</js>, 42), <jv>valueGreaterThanTen</jv>); 933 * </p> 934 * 935 * <h5 class='section'>3. Object Equality (Direct Comparison):</h5> 936 * <p class='bjava'> 937 * <jc>// Non-String, non-Predicate objects use <jsm>Objects.equals</jsm>() comparison</jc> 938 * <jsm>assertMap</jsm>(Map.<jsm>of</jsm>(<js>"key"</js>, <jv>myObject</jv>), <jv>expectedEntry</jv>); 939 * </p> 940 * 941 * <h4 class='section'>Map Ordering Behavior:</h4> 942 * <p>The {@link Listifiers#mapListifier()} method ensures deterministic ordering for map entries:</p> 943 * <ul> 944 * <li><b>{@link SortedMap} (TreeMap, etc.):</b> Preserves existing sort order</li> 945 * <li><b>{@link LinkedHashMap}:</b> Preserves insertion order</li> 946 * <li><b>{@link HashMap} and other unordered Maps:</b> Converts to {@link TreeMap} for natural key ordering</li> 947 * </ul> 948 * <p>This ensures predictable test results regardless of the original map implementation.</p> 949 * 950 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 951 * @param actual The Map to test. Must not be null. 952 * @param expected Multiple arguments of expected map entries. 953 * Can be Strings (readable format comparison), Predicates (functional testing), or Objects (direct equality). 954 * @throws AssertionError if the Map size or contents don't match expected values 955 * @see #assertList(Supplier, Object, Object...) 956 */ 957 public static void assertMap(Supplier<String> message, Map<?,?> actual, Object...expected) { 958 assertList(message, actual, expected); 959 } 960 961 /** 962 * Asserts that mapped property access on an object returns expected values using a custom BiFunction. 963 * 964 * <p>This is designed for testing objects that don't follow 965 * standard JavaBean patterns or require custom property access logic. The BiFunction allows complete 966 * control over how properties are retrieved from the target object.</p> 967 * 968 * <p>This method creates an intermediate LinkedHashMap to collect all property values before 969 * using the same logic as assertBean for comparison. This ensures consistent ordering 970 * and supports the full nested property syntax. The {@link BasicBeanConverter#DEFAULT} is used 971 * for value stringification and nested property access.</p> 972 * 973 * @param <T> The type of object being tested 974 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 975 * @param actual The object to test properties on 976 * @param function The BiFunction that extracts property values. Receives (<jp>object</jp>, <jp>propertyName</jp>) and returns the property value. 977 * @param properties Comma-delimited list of property names to test 978 * @param expected Comma-delimited list of expected values (exceptions become simple class names) 979 * @throws AssertionError if any mapped property values don't match expected values 980 * @see #assertBean(Supplier, Object, String, String) 981 * @see BeanConverter 982 * @see BasicBeanConverter 983 */ 984 public static <T> void assertMapped(Supplier<String> message, T actual, BiFunction<T,String,Object> function, String properties, String expected) { 985 assertNotNull(actual, "Value was null."); 986 reqnn("function", function); 987 reqnn("properties", properties); 988 reqnn("expected", expected); 989 990 var m = new LinkedHashMap<String,Object>(); 991 for (var p : tokenize(properties)) { 992 var pv = p.getValue(); 993 m.put(pv, safe(() -> function.apply(actual, pv))); 994 } 995 996 assertBean(message, m, properties, expected); 997 } 998 999 /** 1000 * Asserts that mapped property access on an object returns expected values using a custom BiFunction. 1001 * 1002 * <p>Same as {@link #assertMapped(Supplier, Object, BiFunction, String, String)} but without a custom message.</p> 1003 * 1004 * @param <T> The type of object being tested 1005 * @param actual The object to test properties on 1006 * @param function The BiFunction that extracts property values. Receives (<jp>object</jp>, <jp>propertyName</jp>) and returns the property value. 1007 * @param properties Comma-delimited list of property names to test 1008 * @param expected Comma-delimited list of expected values (exceptions become simple class names) 1009 * @throws AssertionError if any mapped property values don't match expected values 1010 * @see #assertMapped(Supplier, Object, BiFunction, String, String) 1011 */ 1012 public static <T> void assertMapped(T actual, BiFunction<T,String,Object> function, String properties, String expected) { 1013 assertMapped(null, actual, function, properties, expected); 1014 } 1015 1016 /** 1017 * Asserts that an object's string representation matches the specified glob-style pattern. 1018 * 1019 * <p>Same as {@link #assertMatchesGlob(Supplier, String, Object)} but without a custom message.</p> 1020 * 1021 * @param pattern The glob-style pattern to match against. 1022 * @param value The object to test. Must not be null. 1023 * @throws AssertionError if the value is null or its string representation doesn't match the pattern 1024 * @see #assertMatchesGlob(Supplier, String, Object) 1025 */ 1026 public static void assertMatchesGlob(String pattern, Object value) { 1027 assertMatchesGlob(null, pattern, value); 1028 } 1029 1030 /** 1031 * Asserts that an object's string representation matches the specified glob-style pattern. 1032 * 1033 * <p>This method converts the actual object to its string representation using the current 1034 * {@link BeanConverter} and then tests it against the provided glob-style pattern. 1035 * This is useful for testing string formats with simple wildcard patterns.</p> 1036 * 1037 * <h4 class='section'>Pattern Syntax:</h4> 1038 * <p>The pattern uses glob-style wildcards:</p> 1039 * <ul> 1040 * <li><b>{@code *}</b> matches any sequence of characters (including none)</li> 1041 * <li><b>{@code ?}</b> matches exactly one character</li> 1042 * <li><b>All other characters</b> are treated literally</li> 1043 * </ul> 1044 * 1045 * <h4 class='section'>Usage Examples:</h4> 1046 * <p class='bjava'> 1047 * <jc>// Test filename patterns</jc> 1048 * <jsm>assertMatchesGlob</jsm>(<js>"user_*_temp"</js>, <jv>filename</jv>); 1049 * 1050 * <jc>// Test single character wildcards</jc> 1051 * <jsm>assertMatchesGlob</jsm>(<js>"file?.txt"</js>, <jv>fileName</jv>); 1052 * 1053 * <jc>// Test combined patterns</jc> 1054 * <jsm>assertMatchesGlob</jsm>(<js>"log_*_?.txt"</js>, <jv>logFile</jv>); 1055 * </p> 1056 * 1057 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 1058 * @param pattern The glob-style pattern to match against. 1059 * @param value The object to test. Must not be null. 1060 * @throws AssertionError if the value is null or its string representation doesn't match the pattern 1061 * @see #assertString(Supplier, String, Object) for exact string matching 1062 * @see #assertContains(Supplier, String, Object) for substring matching 1063 */ 1064 public static void assertMatchesGlob(Supplier<String> message, String pattern, Object value) { 1065 reqnn("pattern", pattern); 1066 assertNotNull(value, "Value was null."); 1067 1068 var v = BctConfiguration.getConverter().stringify(value); 1069 var m = StringUtils.getGlobMatchPattern(pattern).matcher(v); 1070 assertTrue(m.matches(), composeMessage(message, "Pattern didn't match. ==> pattern: <%s> but was: <%s>", pattern, v)); 1071 } 1072 1073 /** 1074 * Asserts that a collection-like object, Optional, Value, String, or array is not null and not empty. 1075 * 1076 * <p>Same as {@link #assertNotEmpty(Supplier, Object)} but without a custom message.</p> 1077 * 1078 * @param value The object to test. Must not be null. 1079 * @throws AssertionError if the object is null or empty 1080 * @see #assertNotEmpty(Supplier, Object) 1081 */ 1082 public static void assertNotEmpty(Object value) { 1083 assertNotEmpty(null, value); 1084 } 1085 1086 /** 1087 * Asserts that a collection-like object, Optional, Value, String, or array is not null and not empty. 1088 * 1089 * <p>This method validates that the provided object is not empty according to its type:</p> 1090 * <ul> 1091 * <li><b>String:</b> Must have length > 0</li> 1092 * <li><b>Optional:</b> Must be present (not empty)</li> 1093 * <li><b>Value:</b> Must not be empty (value is not null)</li> 1094 * <li><b>Map:</b> Must have at least one entry</li> 1095 * <li><b>Collection:</b> Must have at least one element</li> 1096 * <li><b>Array:</b> Must have length > 0</li> 1097 * <li><b>Other objects:</b> Must convert to a non-empty List via {@link BeanConverter#listify(Object)}</li> 1098 * </ul> 1099 * 1100 * <h4 class='section'>Supported Types:</h4> 1101 * <p>Any object that can be converted to a List, including:</p> 1102 * <ul> 1103 * <li>Collections (List, Set, Queue, etc.)</li> 1104 * <li>Arrays (primitive and object arrays)</li> 1105 * <li>Iterables, Iterators, Streams</li> 1106 * <li>Maps (converted to list of entries)</li> 1107 * <li>Optional objects</li> 1108 * </ul> 1109 * 1110 * <h4 class='section'>Usage Examples:</h4> 1111 * <p class='bjava'> 1112 * <jc>// Test non-empty collections</jc> 1113 * <jsm>assertNotEmpty</jsm>(List.<jsm>of</jsm>(<js>"item1"</js>, <js>"item2"</js>)); 1114 * <jsm>assertNotEmpty</jsm>(<jk>new</jk> ArrayList<>(Arrays.<jsm>asList</jsm>(<js>"a"</js>))); 1115 * 1116 * <jc>// Test non-empty arrays</jc> 1117 * <jsm>assertNotEmpty</jsm>(<jk>new</jk> String[]{<js>"value"</js>}); 1118 * 1119 * <jc>// Test present Optional</jc> 1120 * <jsm>assertNotEmpty</jsm>(Optional.<jsm>of</jsm>(<js>"value"</js>)); 1121 * 1122 * <jc>// Test non-empty Map</jc> 1123 * <jsm>assertNotEmpty</jsm>(Map.<jsm>of</jsm>(<js>"key"</js>, <js>"value"</js>)); 1124 * </p> 1125 * 1126 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 1127 * @param value The object to test. Must not be null. 1128 * @throws AssertionError if the object is null or empty 1129 * @see #assertEmpty(Supplier, Object) for testing empty collections 1130 * @see #assertSize(Supplier, int, Object) for testing specific sizes 1131 */ 1132 public static void assertNotEmpty(Supplier<String> message, Object value) { 1133 assertNotNull(value, "Value was null."); 1134 int size = BctConfiguration.getConverter().size(value); 1135 assertTrue(size > 0, composeMessage(message, "Value was empty.")); 1136 } 1137 1138 /** 1139 * Asserts that a collection-like object or string is not null and of the specified size. 1140 * 1141 * <p>Same as {@link #assertSize(Supplier, int, Object)} but without a custom message.</p> 1142 * 1143 * @param expected The expected size/length. 1144 * @param actual The object to test. Must not be null. 1145 * @throws AssertionError if the object is null or not the expected size. 1146 * @see #assertSize(Supplier, int, Object) 1147 */ 1148 public static void assertSize(int expected, Object actual) { 1149 assertSize(null, expected, actual); 1150 } 1151 1152 /** 1153 * Asserts that a collection-like object or string is not null and of the specified size. 1154 * 1155 * <p>This method can validate the size of various types of objects:</p> 1156 * <ul> 1157 * <li><b>String:</b> Validates character length</li> 1158 * <li><b>Collection-like objects:</b> Any object that can be converted to a List via the underlying converter</li> 1159 * </ul> 1160 * 1161 * <h4 class='section'>Usage Examples:</h4> 1162 * <p class='bjava'> 1163 * <jc>// Test string length</jc> 1164 * <jsm>assertSize</jsm>(5, <js>"hello"</js>); 1165 * 1166 * <jc>// Test collection size</jc> 1167 * <jsm>assertSize</jsm>(3, List.<jsm>of</jsm>(<js>"a"</js>, <js>"b"</js>, <js>"c"</js>)); 1168 * 1169 * <jc>// Test array size</jc> 1170 * <jsm>assertSize</jsm>(2, <jk>new</jk> String[]{<js>"x"</js>, <js>"y"</js>}); 1171 * </p> 1172 * 1173 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 1174 * @param expected The expected size/length. 1175 * @param actual The object to test. Must not be null. 1176 * @throws AssertionError if the object is null or not the expected size. 1177 */ 1178 public static void assertSize(Supplier<String> message, int expected, Object actual) { 1179 assertNotNull(actual, "Value was null."); 1180 var size = BctConfiguration.getConverter().size(actual); 1181 assertEquals(expected, size, composeMessage(message, "Value not expected size.")); 1182 } 1183 1184 /** 1185 * Asserts that an object's string representation exactly matches the expected value. 1186 * 1187 * <p>Same as {@link #assertString(Supplier, String, Object)} but without a custom message.</p> 1188 * 1189 * @param expected The exact string that the actual object should convert to 1190 * @param actual The object to test. Must not be null. 1191 * @throws AssertionError if the actual object is null or its string representation doesn't exactly match expected 1192 * @see #assertString(Supplier, String, Object) 1193 */ 1194 public static void assertString(String expected, Object actual) { 1195 assertString(null, expected, actual); 1196 } 1197 1198 /** 1199 * Asserts that an object's string representation exactly matches the expected value. 1200 * 1201 * <p>This method converts the actual object to its string representation using the current 1202 * {@link BeanConverter} and performs an exact equality comparison with the expected string. 1203 * This is useful for testing complete string output, formatted objects, or converted values.</p> 1204 * 1205 * <h4 class='section'>Usage Examples:</h4> 1206 * <p class='bjava'> 1207 * <jc>// Test exact string conversion</jc> 1208 * <jsm>assertString</jsm>(<js>"John,30,true"</js>, <jv>user</jv>); <jc>// Assuming user converts to this format</jc> 1209 * 1210 * <jc>// Test formatted dates or numbers</jc> 1211 * <jsm>assertString</jsm>(<js>"2023-12-01"</js>, <jv>localDate</jv>); 1212 * 1213 * <jc>// Test complex object serialization</jc> 1214 * <jsm>assertString</jsm>(<js>"{name=John,age=30}"</js>, <jv>userMap</jv>); 1215 * 1216 * <jc>// Test array/collection formatting</jc> 1217 * <jsm>assertString</jsm>(<js>"[red,green,blue]"</js>, <jv>colors</jv>); 1218 * </p> 1219 * 1220 * @param message Optional custom error message supplier. If provided, will be composed with the default assertion message. 1221 * @param expected The exact string that the actual object should convert to 1222 * @param actual The object to test. Must not be null. 1223 * @throws AssertionError if the actual object is null or its string representation doesn't exactly match expected 1224 * @see #assertContains(Supplier, String, Object) for partial string matching 1225 * @see #assertMatchesGlob(Supplier, String, Object) for pattern-based matching 1226 */ 1227 public static void assertString(Supplier<String> message, String expected, Object actual) { 1228 assertNotNull(actual, "Value was null."); 1229 1230 var messageSupplier = message != null ? message : fs(""); 1231 assertEquals(expected, BctConfiguration.getConverter().stringify(actual), messageSupplier); 1232 } 1233 1234 /** 1235 * Composes an error message from an optional custom message and a default message. 1236 * 1237 * <p>If a custom message is provided, it is composed with the default message in the format: 1238 * <js>"{custom}, Caused by: {default}"</js>. Otherwise, the default message is returned.</p> 1239 * 1240 * @param customMessage Optional custom message supplier. Can be <jk>null</jk>, in which case the default message is returned unmodified. 1241 * @param defaultMessage Default message template. 1242 * @param defaultArgs Arguments for the default message template. 1243 * @return A supplier that produces the composed error message. 1244 */ 1245 private static Supplier<String> composeMessage(Supplier<String> customMessage, String defaultMessage, Object...defaultArgs) { 1246 if (customMessage == null) { 1247 return fs(defaultMessage, defaultArgs); 1248 } 1249 return fs("%s, Caused by: %s", customMessage.get(), f(defaultMessage, defaultArgs)); 1250 } 1251 1252 private BctAssertions() {} 1253}