File size: 218,427 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe "TabCompletion" -Tags CI {
    BeforeAll {
        $separator = [System.IO.Path]::DirectorySeparatorChar
    }

    It 'Should complete Command' {
        $res = TabExpansion2 -inputScript 'Get-Com' -cursorColumn 'Get-Com'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Get-Command'
    }

    It 'Should complete abbreviated cmdlet' {
        $res = (TabExpansion2 -inputScript 'i-psdf' -cursorColumn 'pschr'.Length).CompletionMatches.CompletionText
        $res | Should -HaveCount 1
        $res | Should -BeExactly 'Import-PowerShellDataFile'
    }

    It 'Should complete abbreviated function' {
        function Test-AbbreviatedFunctionExpansion {}
        $res = (TabExpansion2 -inputScript 't-afe' -cursorColumn 't-afe'.Length).CompletionMatches.CompletionText
        $res.Count | Should -BeGreaterOrEqual 1
        $res | Should -BeExactly 'Test-AbbreviatedFunctionExpansion'
    }

    It 'Should complete module by shortname' {
        $res = TabExpansion2 -inputScript 'Get-Module -ListAvailable -Name Host'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Microsoft.PowerShell.Host'
    }

    It 'Should complete native exe' -Skip:(!$IsWindows) {
        $res = TabExpansion2 -inputScript 'notep' -cursorColumn 'notep'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'notepad.exe'
    }

    It 'Should not include duplicate command results' {
        $OldModulePath = $env:PSModulePath
        $tempDir = Join-Path -Path $TestDrive -ChildPath "TempPsModuleDir"
        $ModuleDirs = @(
            Join-Path $tempDir "TestModule1\1.0"
            Join-Path $tempDir "TestModule1\1.1"
            Join-Path $tempDir "TestModule2\1.0"
        )
        try
        {
            foreach ($Dir in $ModuleDirs)
            {
                $NewDir = New-Item -Path $Dir -ItemType Directory -Force
                $ModuleName = $NewDir.Parent.Name
                Set-Content -Value 'MyTestFunction{}' -LiteralPath "$($NewDir.FullName)\$ModuleName.psm1"
                New-ModuleManifest -Path "$($NewDir.FullName)\$ModuleName.psd1" -RootModule "$ModuleName.psm1" -FunctionsToExport "MyTestFunction" -ModuleVersion $NewDir.Name
            }

            $env:PSModulePath += [System.IO.Path]::PathSeparator + $tempDir            
            $Res = TabExpansion2 -inputScript MyTestFunction
            $Res.CompletionMatches.Count | Should -Be 2
            $SortedMatches = $Res.CompletionMatches.CompletionText | Sort-Object
            $SortedMatches[0] | Should -Be "TestModule1\MyTestFunction"
            $SortedMatches[1] | Should -Be "TestModule2\MyTestFunction"
        }
        finally
        {
            $env:PSModulePath = $OldModulePath
            Remove-Item -LiteralPath $ModuleDirs -Recurse -Force
        }
    }

    It 'Should not include duplicate module results' {
        $OldModulePath = $env:PSModulePath
        $tempDir = Join-Path -Path $TestDrive -ChildPath "TempPsModuleDir"
        try
        {
            $ModuleDirs = @(
                Join-Path $tempDir "TestModule1\1.0"
                Join-Path $tempDir "TestModule1\1.1"
            )
            foreach ($Dir in $ModuleDirs)
            {
                $NewDir = New-Item -Path $Dir -ItemType Directory -Force
                $ModuleName = $NewDir.Parent.Name
                Set-Content -Value 'MyTestFunction{}' -LiteralPath "$($NewDir.FullName)\$ModuleName.psm1"
                New-ModuleManifest -Path "$($NewDir.FullName)\$ModuleName.psd1" -RootModule "$ModuleName.psm1" -FunctionsToExport "MyTestFunction" -ModuleVersion $NewDir.Name
            }

            $env:PSModulePath += [System.IO.Path]::PathSeparator + $tempDir            
            $Res = TabExpansion2 -inputScript 'Import-Module -Name TestModule'
            $Res.CompletionMatches.Count | Should -Be 1
            $Res.CompletionMatches[0].CompletionText | Should -Be TestModule1
        }
        finally
        {
            $env:PSModulePath = $OldModulePath
            Remove-Item -LiteralPath $ModuleDirs -Recurse -Force
        }
    }

    It 'Should complete dotnet method' {
        $res = TabExpansion2 -inputScript '(1).ToSt' -cursorColumn '(1).ToSt'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString('
    }

    It 'Should complete dotnet method with null conditional operator' {
        $res = TabExpansion2 -inputScript '(1)?.ToSt' -cursorColumn '(1)?.ToSt'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString('
    }

    It 'Should complete dotnet method with null conditional operator without first letter' {
        $res = TabExpansion2 -inputScript '(1)?.' -cursorColumn '(1)?.'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CompareTo('
    }

    It 'should complete generic type parameters for static methods' {
        $script = '[array]::Empty[pscu'

        $results = TabExpansion2 -inputScript $script -cursorColumn $script.Length
        $results.CompletionMatches.CompletionText | Should -Contain 'pscustomobject'
    }

    It 'should complete generic type parameters for instance methods' {
        $script = '
            $dict = [System.Collections.Concurrent.ConcurrentDictionary[string, int]]::new()
            $dict.AddOrUpdate[pscu'

        $results = TabExpansion2 -inputScript $script -cursorColumn $script.Length
        $results.CompletionMatches.CompletionText | Should -Contain 'pscustomobject'
    }

    It 'Should complete Magic foreach' {
        $res = TabExpansion2 -inputScript '(1..10).Fo' -cursorColumn '(1..10).Fo'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ForEach('
    }

    It "Should complete Magic where" {
        $res = TabExpansion2 -inputScript '(1..10).wh' -cursorColumn '(1..10).wh'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Where('
    }

    It 'Should complete types' {
        $res = TabExpansion2 -inputScript '[pscu' -cursorColumn '[pscu'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'pscustomobject'
    }

    It 'Should complete foreach variable' {
        $res = TabExpansion2 -inputScript 'foreach ($CurrentItem in 1..10){$CurrentIt'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$CurrentItem'
    }

    It 'Should complete variables set with an attribute' {
        $res = TabExpansion2 -inputScript '[ValidateNotNull()]$Var1 = 1; $Var'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1'
    }

    It 'Should use the first type constraint in a variable assignment in the tooltip' {
        $res = TabExpansion2 -inputScript '[int] [string] $Var1 = 1; $Var'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1'
        $res.CompletionMatches[0].ToolTip | Should -BeExactly '[int]$Var1'
    }

    It 'Should not complete parameter name' {
        $res = TabExpansion2 -inputScript 'param($P'
        $res.CompletionMatches.Count | Should -Be 0
    }

    It 'Should complete variable in default value of a parameter' {
        $res = TabExpansion2 -inputScript 'param($PS = $P'
        $res.CompletionMatches.Count | Should -BeGreaterThan 0
    }
    
    It 'Should complete variable with description and value <Value>' -TestCases @(
        @{ Value = 1; Expected = '[int]$VariableWithDescription - Variable description' }
        @{ Value = 'string'; Expected = '[string]$VariableWithDescription - Variable description' }
        @{ Value = $null; Expected = 'VariableWithDescription - Variable description' }
    ) {
        param ($Value, $Expected)
        
        New-Variable -Name VariableWithDescription -Value $Value -Description 'Variable description' -Force
        $res = TabExpansion2 -inputScript '$VariableWithDescription'
        $res.CompletionMatches.Count | Should -Be 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$VariableWithDescription'
        $res.CompletionMatches[0].ToolTip | Should -BeExactly $Expected
    }
    
    It 'Should complete environment variable' {
        try {
            $env:PWSH_TEST_1 = 'value 1'
            $env:PWSH_TEST_2 = 'value 2'

            $res = TabExpansion2 -inputScript '$env:PWSH_TEST_'
            $res.CompletionMatches.Count | Should -Be 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '$env:PWSH_TEST_1'
            $res.CompletionMatches[0].ListItemText | Should -BeExactly 'PWSH_TEST_1'
            $res.CompletionMatches[0].ToolTip | Should -BeExactly 'PWSH_TEST_1'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly '$env:PWSH_TEST_2'
            $res.CompletionMatches[1].ListItemText | Should -BeExactly 'PWSH_TEST_2'
            $res.CompletionMatches[1].ToolTip | Should -BeExactly 'PWSH_TEST_2'
        }
        finally {
            $env:PWSH_TEST_1 = $null
            $env:PWSH_TEST_2 = $null
        }
    }

    It 'Should complete function variable' {
        try {
            Function Test-PwshTest1 {}
            Function Test-PwshTest2 {}

            $res = TabExpansion2 -inputScript '${function:Test-PwshTest'
            $res.CompletionMatches.Count | Should -Be 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '${function:Test-PwshTest1}'
            $res.CompletionMatches[0].ListItemText | Should -BeExactly 'Test-PwshTest1'
            $res.CompletionMatches[0].ToolTip | Should -BeExactly 'Test-PwshTest1'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly '${function:Test-PwshTest2}'
            $res.CompletionMatches[1].ListItemText | Should -BeExactly 'Test-PwshTest2'
            $res.CompletionMatches[1].ToolTip | Should -BeExactly 'Test-PwshTest2'
        }
        finally {
            Remove-Item function:Test-PwshTest1 -ErrorAction SilentlyContinue
            Remove-Item function:Test-PwshTest1 -ErrorAction SilentlyContinue
        }
    }

    It 'Should complete scoped variable with description and value <Value>' -TestCases @(
        @{ Value = 1; Expected = '[int]$VariableWithDescription - Variable description' }
        @{ Value = 'string'; Expected = '[string]$VariableWithDescription - Variable description' }
        @{ Value = $null; Expected = 'VariableWithDescription - Variable description' }
    ) {
        param ($Value, $Expected)
        
        New-Variable -Name VariableWithDescription -Value $Value -Description 'Variable description' -Force
        $res = TabExpansion2 -inputScript '$local:VariableWithDescription'
        $res.CompletionMatches.Count | Should -Be 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$local:VariableWithDescription'
        $res.CompletionMatches[0].ToolTip | Should -BeExactly $Expected
    }

    It 'Should not complete property name in class definition' {
        $res = TabExpansion2 -inputScript 'class X {$P'
        $res.CompletionMatches.Count | Should -Be 0
    }

    foreach ($Operator in [System.Management.Automation.CompletionCompleters]::CompleteOperator(""))
    {
        It "Should complete $($Operator.CompletionText)" {
            $res = TabExpansion2 -inputScript "'' $($Operator.CompletionText)" -cursorColumn ($Operator.CompletionText.Length + 3)
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $Operator.CompletionText
        }
    }

    context CustomProviderTests {
        BeforeAll {
            $testModulePath = Join-Path $TestDrive "ReproModule"
            New-Item -Path $testModulePath -ItemType Directory > $null

            New-ModuleManifest -Path "$testModulePath/ReproModule.psd1" -RootModule 'testmodule.dll'

            $testBinaryModulePath = Join-Path $testModulePath "testmodule.dll"
            $binaryModule = @'
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Provider;

namespace BugRepro
{
    public class IntItemInfo
    {
        public string Name;
        public IntItemInfo(string name) => Name = name;
    }

    [CmdletProvider("Int", ProviderCapabilities.None)]
    public class IntProvider : NavigationCmdletProvider
    {
        public static string[] ToChunks(string path) => path.Split("/", StringSplitOptions.RemoveEmptyEntries);

        protected string _ChildName(string path)
        {
            var name = ToChunks(path).LastOrDefault();
            return name ?? string.Empty;
        }

        protected string Normalize(string path) => string.Join("/", ToChunks(path));

        protected override string GetChildName(string path)
        {
            var name = _ChildName(path);
            // if (!IsItemContainer(path)) { return string.Empty; }
            return name;
        }

        protected override bool IsValidPath(string path) => int.TryParse(GetChildName(path), out int _);

        protected override bool IsItemContainer(string path)
        {
            var name = _ChildName(path);
            if (!int.TryParse(name, out int value))
            {
                return false;
            }
            if (ToChunks(path).Count() > 3)
            {
                return false;
            }
            return value % 2 == 0;
        }

        protected override bool ItemExists(string path)
        {
            foreach (var chunk in ToChunks(path))
            {
                if (!int.TryParse(chunk, out int value))
                {
                    return false;
                }
                if (value < 0 || value > 9)
                {
                    return false;
                }
            }
            return true;
        }

        protected override void GetItem(string path)
        {
            var name = GetChildName(path);
            if (!int.TryParse(name, out int _))
            {
                return;
            }
            WriteItemObject(new IntItemInfo(name), path, IsItemContainer(path));
        }
        protected override bool HasChildItems(string path) => IsItemContainer(path);

        protected override void GetChildItems(string path, bool recurse)
        {
            if (!IsItemContainer(path)) { GetItem(path); return; }

            for (var i = 0; i <= 9; i++)
            {
                var _path = $"{Normalize(path)}/{i}";
                if (recurse)
                {
                    GetChildItems(_path, recurse);
                }
                else
                {
                    GetItem(_path);
                }
            }
        }
    }
}
'@
            Add-Type -OutputAssembly $testBinaryModulePath -TypeDefinition $binaryModule

            $pwsh = "$PSHOME\pwsh"
        }

        It "Should not complete invalid items when a provider path returns itself instead of its children" {
            $result = & $pwsh -NoProfile -Command "Import-Module -Name $testModulePath; (TabExpansion2 'Get-ChildItem Int::/2/3/').CompletionMatches.Count"
            $result | Should -BeExactly "0"
        }
    }

    It 'should complete index expression for <Intent>' -TestCases @(
        @{
            Intent = 'Hashtable with no user input'
            Expected = "'PSVersion'"
            TestString = '$PSVersionTable[^'
        }
        @{
            Intent = 'Hashtable with partial input'
            Expected = "'PSVersion'"
            TestString = '$PSVersionTable[ PSvers^'
        }
        @{
            Intent = 'Hashtable with partial quoted input'
            Expected = "'PSVersion'"
            TestString = '$PSVersionTable["PSvers^'
        }
        @{
            Intent = 'Hashtable from Ast'
            Expected = "'Hello'"
            TestString = '$Table = @{Hello = "World"};$Table[^'
        }
        @{
            Intent = 'Hashtable with cursor on new line'
            Expected = "'Hello'"
            TestString = @'
$Table = @{Hello = "World"}
$Table[
^
'@
        }
    ) -Test {
        param($Expected, $TestString)
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.CompletionMatches[0].CompletionText | Should -BeExactly $Expected
    }

    it 'should add quotes when completing hashtable key from Ast with member syntax' -Test {
        $res = TabExpansion2 -inputScript '$Table = @{"Hello World" = "World"};$Table.'
        $res.CompletionMatches.CompletionText | Where-Object {$_ -eq "'Hello World'"} | Should -BeExactly "'Hello World'"
    }

    It '<Intent>' -TestCases @(
        @{
            Intent = 'Complete member with space between dot and cursor'
            Expected = 'value__'
            TestString = '[System.Management.Automation.ActionPreference]::Break.  ^'
        }
        @{
            Intent = 'Complete member when cursor is in-between existing members and spaces'
            Expected = 'value__'
            TestString = '[System.Management.Automation.ActionPreference]::Break. ^ ToString()'
        }
        @{
            Intent = 'Complete static member with space between colons and cursor'
            Expected = 'Break'
            TestString = '[System.Management.Automation.ActionPreference]::  ^'
        }
        @{
            Intent = 'Complete static member with new line between colons and cursor'
            Expected = 'Break'
            TestString = @'
[System.Management.Automation.ActionPreference]::
^
'@
        }
        @{
            Intent = 'Complete static member with partial input and incomplete input at end of line'
            Expected = 'Break'
            TestString = '[System.Management.Automation.ActionPreference]::  Brea^.   value__.'
        }
        @{
            Intent = 'Complete static member with partial input and valid input at end of line'
            Expected = 'Break'
            TestString = '[System.Management.Automation.ActionPreference]::  Brea^.   value__'
        }
        @{
            Intent = 'Complete member with new line between colons and cursor'
            Expected = 'value__'
            TestString = '[System.Management.Automation.ActionPreference]::Break. ^ ToString()'
        }
        @{
            Intent = 'Complete type with incomplete expression input at end of line'
            Expected = 'System.Management.Automation.ActionPreference'
            TestString = '[System.Management.Automation.ActionPreference^]::'
        }
        @{
            Intent = 'Complete member inside switch expression'
            Expected = 'Length'
            TestString = @'
switch ($x)
{
    'RandomString'.^
    {}
}
'@
        }
        @{
            Intent = 'Complete member in commandast'
            Expected = 'Length'
            TestString = 'ls "".^'
        }
        ){
            param($Expected, $TestString)
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $Expected
        }

    It 'Should Complete and replace existing member with space in front of cursor and cursor in front of word' {
        $TestString = '[System.Management.Automation.ActionPreference]:: ^Break'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.ReplacementIndex | Should -BeExactly $CursorIndex
        $res.ReplacementLength | Should -Be 5
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Break'
    }

    It 'Complete and replace existing member with colons in front of cursor and cursor in front of word' {
        $TestString = '[System.Management.Automation.ActionPreference]::^Break'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.ReplacementIndex | Should -BeExactly $CursorIndex
        $res.ReplacementLength | Should -Be 5
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Break'
    }

    It 'Should complete namespaces' {
        $res = TabExpansion2 -inputScript 'using namespace Sys' -cursorColumn 'using namespace Sys'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'System'
    }

    It 'Should complete format-table hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Table @{ ' -cursorColumn 'Get-ChildItem | Format-Table @{ '.Length
        $res.CompletionMatches | Should -HaveCount 5
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Alignment Expression FormatString Label Width'
    }

    It 'Should complete format-* hashtable on GroupBy: <cmd>' -TestCases (
        @{cmd = 'Format-Table'},
        @{cmd = 'Format-List'},
        @{cmd = 'Format-Wide'},
        @{cmd = 'Format-Custom'}
    ) {
        param($cmd)
        $res = TabExpansion2 -inputScript "Get-ChildItem | $cmd -GroupBy @{ " -cursorColumn "Get-ChildItem | $cmd -GroupBy @{ ".Length
        $res.CompletionMatches | Should -HaveCount 3
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Expression FormatString Label'
    }

    It 'Should complete format-list hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-List @{ ' -cursorColumn 'Get-ChildItem | Format-List @{ '.Length
        $res.CompletionMatches | Should -HaveCount 3
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Expression FormatString Label'
    }

    It 'Should complete format-wide hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Wide @{ ' -cursorColumn 'Get-ChildItem | Format-Wide @{ '.Length
        $res.CompletionMatches | Should -HaveCount 2
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Expression FormatString'
    }

    It 'Should complete format-custom hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Custom @{ ' -cursorColumn 'Get-ChildItem | Format-Custom @{ '.Length
        $res.CompletionMatches | Should -HaveCount 2
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Depth Expression'
    }

    It 'Should complete Select-Object hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Select-Object @{ ' -cursorColumn 'Get-ChildItem | Select-Object @{ '.Length
        $res.CompletionMatches | Should -HaveCount 2
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Expression Name'
    }

    It 'Should complete Sort-Object hashtable' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Sort-Object @{ ' -cursorColumn 'Get-ChildItem | Sort-Object @{ '.Length
        $res.CompletionMatches | Should -HaveCount 3
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Ascending Descending Expression'
    }

    It 'Should complete variable assigned in other scriptblock' {
        $res = TabExpansion2 -inputScript 'ForEach-Object -Begin {$Test1 = "Hello"} -Process {$Test'
        $res.CompletionMatches[0].CompletionText | Should -Be '$Test1'
    }

    It 'Should complete variable assigned in an array of scriptblocks' {
        $res = TabExpansion2 -inputScript 'ForEach-Object -Process @({"Block1"},{$Test1="Hello"});$Test'
        $res.CompletionMatches[0].CompletionText | Should -Be '$Test1'
    }

    It 'Should not complete variable assigned in an ampersand executed scriptblock' {
        $res = TabExpansion2 -inputScript '& {$AmpeersandVarCompletionTest = "Hello"};$AmpeersandVarCompletionTes'
        $res.CompletionMatches.Count | Should -Be 0
    }

    It 'Should complete variable assigned in command redirection to variable' {
        $res = TabExpansion2 -inputScript 'New-Guid 1>variable:Redir1 2>variable:Redir2 3>variable:Redir3 4>variable:Redir4 5>variable:Redir5 6>variable:Redir6; $Redir'
        $res.CompletionMatches[0].CompletionText | Should -Be '$Redir1'
        $res.CompletionMatches[1].CompletionText | Should -Be '$Redir2'
        $res.CompletionMatches[1].ToolTip | Should -Be '[ErrorRecord]$Redir2'
        $res.CompletionMatches[2].CompletionText | Should -Be '$Redir3'
        $res.CompletionMatches[2].ToolTip | Should -Be '[WarningRecord]$Redir3'
        $res.CompletionMatches[3].CompletionText | Should -Be '$Redir4'
        $res.CompletionMatches[3].ToolTip | Should -Be '[VerboseRecord]$Redir4'
        $res.CompletionMatches[4].CompletionText | Should -Be '$Redir5'
        $res.CompletionMatches[4].ToolTip | Should -Be '[DebugRecord]$Redir5'
        $res.CompletionMatches[5].CompletionText | Should -Be '$Redir6'
        $res.CompletionMatches[5].ToolTip | Should -Be '[InformationRecord]$Redir6'
    }

    context TypeConstructionWithHashtable {
        BeforeAll {
            class RandomTestType {
                $A
                $B
                $C
            }
            function RandomTestTypeClassTestCompletion([RandomTestType]$Param1){}
            Class LevelOneClass {
                [LevelTwoClass] $Property1
            }
            class LevelTwoClass {
                [string] $Property2
            }
            function LevelOneClassTestCompletion([LevelOneClass[]]$Param1){}
            Add-Type -TypeDefinition 'public interface IRandomInterfaceTest{string DemoProperty { get; set; }}'
            function functionWithInterfaceParam ([IRandomInterfaceTest]$Param1){}
        }
        It 'Should complete New-Object hashtable' {
            $res = TabExpansion2 -inputScript 'New-Object -TypeName RandomTestType -Property @{ '
            $res.CompletionMatches | Should -HaveCount 3
            $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C'
        }

        It 'Complete hashtable key without duplicate keys' {
            $TestString = '[RandomTestType]@{A="";^}'
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'B C'
        }

        It 'Complete hashtable key on empty line after key/value pair' {
            $TestString = @'
[RandomTestType]@{
    B=""
    ^
}
'@
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A C'
        }

        It 'Should complete class properties for typed variable declaration with hashtable' {
            $res = TabExpansion2 -inputScript '[RandomTestType]$TestVar = @{'
            $res.CompletionMatches | Should -HaveCount 3
            $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C'
        }

        It 'Should complete class properties for typed command parameter with hashtable input' {
            $res = TabExpansion2 -inputScript 'RandomTestTypeClassTestCompletion -Param1 @{'
            $res.CompletionMatches | Should -HaveCount 3
            $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C'
        }

        It 'Should complete class properties for nested hashtable' {
            $res = TabExpansion2 -inputScript '[LevelOneClass]@{Property1=@{'
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2'
        }

        It 'Should complete class properties for underlying type in array parameter' {
            $res = TabExpansion2 -inputScript 'LevelOneClassTestCompletion @{'
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property1'
        }

        It 'Should complete class properties for new class assignment to property' {
            $res = TabExpansion2 -inputScript '$Var=[LevelOneClass]::new();$Var.Property1=@{'
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2'
        }

        It 'Should not complete class properties from class with constructor that takes arguments' {
            $res = TabExpansion2 -inputScript 'class ClassWithCustomConstructor {ClassWithCustomConstructor ($Param){}$A};[ClassWithCustomConstructor]@{'
            $res.CompletionMatches[0].CompletionText | Should -BeNullOrEmpty
        }

        It 'Should complete class properties for function with an interface type' {
            $res = TabExpansion2 -inputScript 'functionWithInterfaceParam -Param1 @{'
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'DemoProperty'
        }
    }

    It 'Complete hashtable keys for Get-WinEvent FilterHashtable' -Skip:(!$IsWindows) {
        $TestString = 'Get-WinEvent -FilterHashtable @{^'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
        $res.CompletionMatches | Should -HaveCount 11
        $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data SuppressHashFilter'
    }

    It 'Complete hashtable keys for Get-WinEvent SuppressHashFilter' -Skip:(!$IsWindows) {
        $TestString = 'Get-WinEvent -FilterHashtable @{SuppressHashFilter=@{'
        $res = TabExpansion2 -inputScript $TestString
        $res.CompletionMatches | Should -HaveCount 10
        $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data'
    }

    It 'Complete hashtable keys for hashtable in array of arguments' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Table -Property Attributes,@{'
        $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'Expression FormatString Label Width Alignment'
    }

    It 'Complete hashtable keys for a hashtable used for splatting' {
        $TestString = '$GetChildItemParams=@{^};Get-ChildItem @GetChildItemParams -Force -Recurse'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Path'
    }

    It 'Should complete "Get-Process -Id " with Id and name in tooltip' {
        Set-StrictMode -Version 3.0
        $cmd = 'Get-Process -Id '
        [System.Management.Automation.CommandCompletion]$res = TabExpansion2 -inputScript $cmd  -cursorColumn $cmd.Length
        $res.CompletionMatches[0].CompletionText -match '^\d+$' | Should -BeTrue
        $res.CompletionMatches[0].ListItemText -match '^\d+ -' | Should -BeTrue
        $res.CompletionMatches[0].ToolTip -match '^\d+ -' | Should -BeTrue
    }

    It 'Should complete "Get-Process" with process names' {
        $cmd = "Get-Process "
        $res = TabExpansion2 -inputScript $cmd  -cursorColumn $cmd.Length
        # Can't compare to number of processes since macOS has a large number of processes
        # that have empty Name which should be skipped
        $res.CompletionMatches.Count | Should -BeGreaterThan 0
    }

    It 'Should complete keyword with partial input' {
        $res = TabExpansion2 -inputScript 'using nam' -cursorColumn 'using nam'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'namespace'
    }

    It 'Should complete keyword with no input' {
        $res = TabExpansion2 -inputScript 'using ' -cursorColumn 'using '.Length
        $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type'
    }

    It 'Should complete keyword with no input after line continuation' {
        $InputScript = @'
using `

'@
        $res = TabExpansion2 -inputScript $InputScript -cursorColumn $InputScript.Length
        $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type'
    }

    It 'Should first suggest -Full and then -Functionality when using Get-Help -Fu<tab>' -Skip {
        $res = TabExpansion2 -inputScript 'Get-Help -Fu' -cursorColumn 'Get-Help -Fu'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full'
        $res.CompletionMatches[1].CompletionText | Should -BeExactly '-Functionality'
    }

    It 'Should first suggest -Full and then -Functionality when using help -Fu<tab>' -Skip {
        $res = TabExpansion2 -inputScript 'help -Fu' -cursorColumn 'help -Fu'.Length
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full'
        $res.CompletionMatches[1].CompletionText | Should -BeExactly '-Functionality'
    }

    It 'Should not remove braces when completing variable with braces' {
        $Text = '"Hello${psversiont}World"'
        $res = TabExpansion2 -inputScript $Text -cursorColumn $Text.IndexOf('p')
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '${PSVersionTable}'
    }

    It 'Should work for property assignment of enum type:' {
        $res = TabExpansion2 -inputScript '$psstyle.Progress.View="Clas'
        $res.CompletionMatches[0].CompletionText | Should -Be '"Classic"'
    }

    It 'Should work for variable assignment of enum type with type inference' {
        $res = TabExpansion2 -inputScript '[System.Management.Automation.ProgressView]$MyUnassignedVar = $psstyle.Progress.View; $MyUnassignedVar = "Class'
        $res.CompletionMatches[0].CompletionText | Should -Be '"Classic"'
    }

    It 'Should work for property assignment of enum type with type inference with PowerShell class' {
        $res = TabExpansion2 -inputScript 'enum Animals{Cat= 0;Dog= 1};class AnimalTestClass{[Animals] $Prop1};$Test1 = [AnimalTestClass]::new();$Test1.Prop1 = "C'
        $res.CompletionMatches[0].CompletionText | Should -Be '"Cat"'
    }

    It 'Should work for variable assignment with type inference of PowerShell Enum' {
        $res = TabExpansion2 -inputScript 'enum Animals{Cat= 0;Dog= 1}; [Animals]$TestVar1 = "D'
        $res.CompletionMatches[0].CompletionText | Should -Be '"Dog"'
    }

    It 'Should work for variable assignment of enum type: <inputStr>' -TestCases @(
        @{ inputStr = '$ErrorActionPreference = '; filter = ''; doubleQuotes = $false }
        @{ inputStr = '$ErrorActionPreference='; filter = ''; doubleQuotes = $false }
        @{ inputStr = '$ErrorActionPreference="'; filter = ''; doubleQuotes = $true }
        @{ inputStr = '$ErrorActionPreference = ''s'; filter = '| Where-Object { $_ -like "''s*" }'; doubleQuotes = $false }
        @{ inputStr = '$ErrorActionPreference = "siL'; filter = '| Where-Object { $_ -like ''"sil*'' }'; doubleQuotes = $true }
        @{ inputStr = '[System.Management.Automation.ActionPreference]$e='; filter = ''; doubleQuotes = $false }
        @{ inputStr = '[System.Management.Automation.ActionPreference]$e = '; filter = ''; doubleQuotes = $false }
        @{ inputStr = '[System.Management.Automation.ActionPreference]$e = "'; filter = ''; doubleQuotes = $true }
        @{ inputStr = '[System.Management.Automation.ActionPreference]$e = "s'; filter = '| Where-Object { $_ -like """s*" }'; doubleQuotes = $true }
        @{ inputStr = '[System.Management.Automation.ActionPreference]$e = "x'; filter = '| Where-Object { $_ -like """x*" }'; doubleQuotes = $true }
    ){
        param($inputStr, $filter, $doubleQuotes)

        $quote = ''''
        if ($doubleQuotes) {
            $quote = '"'
        }

        $sb = [scriptblock]::Create(@"
            [cmdletbinding()] param([Parameter(ValueFromPipeline=`$true)]`$obj) process { `$obj $filter }
"@)

        $expectedValues = [enum]::GetValues("System.Management.Automation.ActionPreference") | ForEach-Object { $quote + $_.ToString() + $quote } | & $sb | Sort-Object
        if ($expectedValues.Count -gt 0) {
            $expected = [string]::Join(",",$expectedValues)
        }
        else {
            $expected = ''
        }

        $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
        if ($res.CompletionMatches.Count -gt 0) {
            $actual = [string]::Join(",",$res.CompletionMatches.completiontext)
        }
        else {
            $actual = ''
        }

        $actual | Should -BeExactly $expected
    }

    It 'Should work for variable assignment of custom enum: <inputStr>' -TestCases @(
        @{ inputStr = '[Animal]$c="g'; expected = '"Giraffe"','"Goose"' }
        @{ inputStr = '[Animal]$c='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" }
        @{ inputStr = '$script:test = "g'; expected = '"Giraffe"','"Goose"' }
        @{ inputStr = '$script:test='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" }
        @{ inputStr = '$script:test = "x'; expected = @() }
    ){
        param($inputStr, $expected)

        enum Animal { Duck; Goose; Horse; Giraffe }
        [Animal]$script:test = 'Duck'

        $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
        if ($res.CompletionMatches.Count -gt 0) {
            $actual = [string]::Join(",",$res.CompletionMatches.completiontext)
        }
        else {
            $actual = ''
        }

        $actual | Should -BeExactly ([string]::Join(",",$expected))
    }

    It 'Should work for assignment of variable with validateset of strings: <inputStr>' -TestCases @(
        @{ inputStr = '$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false }
        @{ inputStr = '$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true }
        @{ inputStr = '$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true }
        @{ inputStr = '$test=''aab'; expected = "'aab'"; doubleQuotes = $false }
        @{ inputStr = '$test="c'; expected = ''; doubleQuotes = $true }
    ){
        param($inputStr, $expected, $doubleQuotes)

        [ValidateSet('a','aa','aab','b')][string]$test = 'b'

        $expected = [string]::Join(",",$expected)
        if ($doubleQuotes) {
            $expected = $expected.Replace("'", """")
        }

        $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
        if ($res.CompletionMatches.Count -gt 0) {
            $actual = [string]::Join(",",$res.CompletionMatches.completiontext)
        }
        else {
            $actual = ''
        }

        $actual | Should -BeExactly $expected
    }

    It 'Should work for assignment of variable with validateset of int: <inputStr>' -TestCases @(
        @{ inputStr = '$test='; expected = 2,3,11,112 }
        @{ inputStr = '$test = 1'; expected = 11,112 }
        @{ inputStr = '$test =11'; expected = 11,112 }
        @{ inputStr = '$test =4'; expected = @() }
    ){
        param($inputStr, $expected)

        [ValidateSet(2,3,11,112)][int]$test = 2

        $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
        if ($res.CompletionMatches.Count -gt 0) {
            $actual = [string]::Join(",",$res.CompletionMatches.completiontext)
        }
        else {
            $actual = ''
        }

        $actual | Should -BeExactly ([string]::Join(",",$expected))
    }

    It 'Should work for assignment of variable with validateset of strings: <inputStr>' -TestCases @(
        @{ inputStr = '[validateset("a","aa","aab","b")][string]$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false }
        @{ inputStr = '[validateset("a","aa","aab","b")][string]$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true }
        @{ inputStr = '[validateset("a","aa","aab","b")][string]$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true }
        @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''aab'; expected = "'aab'"; doubleQuotes = $false }
        @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''c'; expected = ''; doubleQuotes = $false }
    ){
        param($inputStr, $expected, $doubleQuotes)

        $expected = [string]::Join(",",$expected)
        if ($doubleQuotes) {
            $expected = $expected.Replace("'", """")
        }

        $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
        if ($res.CompletionMatches.Count -gt 0) {
            $actual = [string]::Join(",",$res.CompletionMatches.completiontext)
        }
        else {
            $actual = ''
        }

        $actual | Should -BeExactly $expected
    }

    It 'ForEach-Object member completion results should include methods' {
        $res = TabExpansion2 -inputScript '1..10 | ForEach-Object -MemberName '
        $res.CompletionMatches.CompletionText | Should -Contain "GetType"
    }

    It 'Should complete variable member inferred from command inside scriptblock' {
        $res = TabExpansion2 -inputScript '& {(New-Guid).'
        $res.CompletionMatches.Count | Should -BeGreaterThan 0
    }

    It 'Should not complete void instance members' {
        $res = TabExpansion2 -inputScript '([void]("")).'
        $res.CompletionMatches | Should -BeNullOrEmpty
    }

    It 'Should complete custom constructor from class using the AST' {
        $res = TabExpansion2 -inputScript 'class ConstructorTestClass{ConstructorTestClass ([string] $s){}};[ConstructorTestClass]::'
        $res.CompletionMatches | Should -HaveCount 3
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'Equals( new( ReferenceEquals('
    }

    It 'Should complete variables assigned inside do while loop' {
        $TestString =  'do{$Var1 = 1; $Var^ }while ($true)'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1'
    }

    It 'Should complete variables assigned inside do until loop' {
        $TestString =  'do{$Var1 = 1; $Var^ }until ($null = Get-ChildItem)'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1'
    }

    It 'Should show multiple constructors in the tooltip' {
        $res = TabExpansion2 -inputScript 'class ConstructorTestClass{ConstructorTestClass ([string] $s){}ConstructorTestClass ([int] $i){}ConstructorTestClass ([int] $i, [bool]$b){}};[ConstructorTestClass]::new'
        $res.CompletionMatches | Should -HaveCount 1
        $completionText = $res.CompletionMatches.ToolTip
        $completionText.replace("`r`n", [System.Environment]::NewLine).trim()

        $expected = @'
ConstructorTestClass(string s)
ConstructorTestClass(int i)
ConstructorTestClass(int i, bool b)
'@
        $expected.replace("`r`n", [System.Environment]::NewLine).trim()
        $completionText.replace("`r`n", [System.Environment]::NewLine).trim() | Should -BeExactly $expected
    }

    It 'Should complete parameter in param block' {
        $res = TabExpansion2 -inputScript 'Param($Param1=(Get-ChildItem -))' -cursorColumn 30
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Path'
    }

    It 'Should complete member in param block' {
        $res = TabExpansion2 -inputScript 'Param($Param1=($PSVersionTable.))' -cursorColumn 31
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Count'
    }

    It 'Should complete attribute argument in param block' {
        $res = TabExpansion2 -inputScript 'Param([Parameter()]$Param1)' -cursorColumn 17
        $names = [Parameter].GetProperties() | Where-Object CanWrite | ForEach-Object Name

        $diffs = Compare-Object -ReferenceObject $res.CompletionMatches.CompletionText -DifferenceObject $names
        $diffs | Should -BeNullOrEmpty
    }

    It 'Should complete attribute argument in incomplete param block' {
        $res = TabExpansion2 -inputScript 'param([ValidatePattern('
        $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ','
        $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected
    }

    It 'Should complete attribute argument in incomplete param block on new line' {
        $TestString =  @'
param([ValidatePattern(
^)])
'@
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ','
        $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected
    }

    It 'Should complete attribute argument with partially written name in incomplete param block' {
        $TestString =  'param([ValidatePattern(op^)]'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Options'
    }

    It 'Should complete attribute argument for incomplete standalone attribute' {
        $res = TabExpansion2 -inputScript '[ValidatePattern('
        $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ','
        $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected
    }

    It 'Should complete argument for second parameter' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem -Path $HOME -ErrorAction '
        $res.CompletionMatches[0].CompletionText | Should -BeExactly Break
    }

    It 'Should complete argument with validateset attribute after comma' {
        $TestString = 'function Test-ValidateSet{Param([ValidateSet("Cat","Dog")]$Param1,$Param2)};Test-ValidateSet -Param1 Dog, -Param2'
        $res = TabExpansion2 -inputScript $TestString -cursorColumn ($TestString.LastIndexOf(',') + 1)
        $res.CompletionMatches[0].CompletionText | Should -BeExactly Cat
    }

    It 'Should complete cim ETS member added by shortname' -Skip:(!$IsWindows -or (Test-IsWinServer2012R2) -or (Test-IsWindows2016)) {
        $res = TabExpansion2 -inputScript '(Get-NetFirewallRule).Nam'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Name'
    }

    It 'Should complete variable assigned with Data statement' {
        $TestString = 'data MyDataVar {"Hello"};$MyDatav'
        $res = TabExpansion2 -inputScript $TestString
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$MyDataVar'
    }

    It 'Should complete global variable without scope' {
        $res = TabExpansion2 -inputScript '$Global:MyTestVar = "Hello";$MyTestV'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$MyTestVar'
    }

    It 'Should complete previously assigned variable in using: scope' {
        $res = TabExpansion2 -inputScript '$MyTestVar = "Hello";$Using:MyTestv'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Using:MyTestVar'
    }

    it 'Should complete "Value" parameter value in "Where-Object" for Enum property with no input' {
        $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -eq '
        $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias
    }

    it 'Should complete "Value" parameter value in "Where-Object" for Enum property with partial input' {
        $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -ne Ali'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias
    }

    it 'Should complete the right hand side of a comparison operator when left is an Enum with no input' {
        $res = TabExpansion2 -inputScript 'Get-Command | Where-Object -FilterScript {$_.CommandType -like '
        $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'"
    }

    it 'Should complete the right hand side of a comparison operator when left is an Enum with partial input' {
        $TempVar = Get-Command
        $res = TabExpansion2 -inputScript '$tempVar[0].CommandType -notlike "Ali"'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'"
    }

    it 'Should complete the right hand side of a comparison operator when left is an Enum when cursor is on a newline' {
        $res = TabExpansion2 -inputScript "Get-Command | Where-Object -FilterScript {`$_.CommandType -like`n"
        $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'"
    }

    it 'Should complete provider dynamic parameters with quoted path' {
        $Script = if ($IsWindows)
        {
            'Get-ChildItem -Path "C:\" -Director'
        }
        else
        {
            'Get-ChildItem -Path "/" -Director'
        }
        $res = TabExpansion2 -inputScript $Script
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Directory'
    }

    it 'Should complete dynamic parameters while providing values to non-string parameters' {
        $res = TabExpansion2 -inputScript 'Get-Content -Path $HOME -Verbose:$false -'
        $res.CompletionMatches.CompletionText | Should -Contain '-Raw'
    }

    It 'Should enumerate types when completing member names for Select-Object' {
        $TestString = '"Hello","World" | select-object '
        $res = TabExpansion2 -inputScript $TestString
        $res | Should -HaveCount 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Length'
    }

    It 'Should complete psobject members for variable' {
        $TestVar = Get-Command Get-Command | Select-Object CommandType
        $res = TabExpansion2 -inputScript '$TestVar | ForEach-Object {$_.commandtype'
        $res | Should -HaveCount 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CommandType'
    }

    It 'Should not complete variables that appear after the cursor' {
        $TestString = '$TestVar1 = 1; $TestVar^ ; $TestVar2 = 2'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res | Should -HaveCount 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1'
    }

    It 'Should not complete pipeline variables outside the pipeline' {
        $TestString = 'Get-ChildItem -PipelineVariable TestVar1;$TestVar^'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res.CompletionMatches | Should -HaveCount 0
    }

    It 'Should complete pipeline variables inside the pipeline' {
        $TestString = 'Get-ChildItem -PipelineVariable TestVar1 | ForEach-Object -Process {$TestVar^}'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
        $res | Should -HaveCount 1
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1'
    }

    It 'Should complete variable assigned in ParenExpression' {
        $res = TabExpansion2 -inputScript '($ParenVar) = 1; $ParenVa'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$ParenVar'
    }

    It 'Should complete variable assigned in ArrayLiteral' {
        $res = TabExpansion2 -inputScript '$DemoVar1, $DemoVar2 = 1..10; $DemoVar'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly '$DemoVar1'
        $res.CompletionMatches[1].CompletionText | Should -BeExactly '$DemoVar2'
    }

    It 'Should include parameter help message in tool tip - SingleMatch <SingleMatch>' -TestCases @(
        @{ SingleMatch = $true }
        @{ SingleMatch = $false }
    ) {
        param ($SingleMatch)

        Function Test-Function {
            param (
                [Parameter(HelpMessage = 'Some help message')]
                $ParamWithHelp,

                $ParamWithoutHelp
            )
        }

        $expected = '[Object] ParamWithHelp - Some help message'

        if ($SingleMatch) {
            $Script = 'Test-Function -ParamWithHelp'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches
        }
        else {
            $Script = 'Test-Function -'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-ParamWithHelp'
        }

        $res.Count | Should -Be 1
        $res.CompletionText | Should -BeExactly '-ParamWithHelp'
        $res.ToolTip | Should -BeExactly $expected
    }

    It 'Should include parameter help resource message in tool tip - SingleMatch <SingleMatch>' -TestCases @(
        @{ SingleMatch = $true }
        @{ SingleMatch = $false }
    ) {
        param ($SingleMatch)

        $expected = '`[string`] Activity - *'

        if ($SingleMatch) {
            $Script = 'Write-Progress -Activity'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches
        }
        else {
            $Script = 'Write-Progress -'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-Activity'
        }

        $res.Count | Should -Be 1
        $res.CompletionText | Should -BeExactly '-Activity'
        $res.ToolTip | Should -BeLikeExactly $expected
    }

    It 'Should skip empty parameter HelpMessage with multiple parameters - SingleMatch <SingleMatch>' -TestCases @(
        @{ SingleMatch = $true }
        @{ SingleMatch = $false }
    ) {
        param ($SingleMatch)

        Function Test-Function {
            [CmdletBinding(DefaultParameterSetName = 'SetWithoutHelp')]
            param (
                [Parameter(ParameterSetName = 'SetWithHelp', HelpMessage = 'Help Message')]
                [Parameter(ParameterSetName = 'SetWithoutHelp')]
                [string]
                $ParamWithHelp,
                
                [Parameter(ParameterSetName = 'SetWithHelp')]
                [switch]
                $ParamWithoutHelp
            )
        }

        $expected = '[string] ParamWithHelp - Help Message'

        if ($SingleMatch) {
            $Script = 'Test-Function -ParamWithHelp'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches
        }
        else {
            $Script = 'Test-Function -'
            $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-ParamWithHelp'
        }

        $res.Count | Should -Be 1
        $res.CompletionText | Should -BeExactly '-ParamWithHelp'
        $res.ToolTip | Should -BeExactly $expected
    }

    It 'Should retrieve help message from dynamic parameter' {
        Function Test-Function {
            [CmdletBinding()]
            param ()
            dynamicparam {
                $attr = [System.Management.Automation.ParameterAttribute]@{
                    HelpMessage = "Howdy partner"
                }
                $attrCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
                $attrCollection.Add($attr)

                $dynParam = [System.Management.Automation.RuntimeDefinedParameter]::new('DynamicParam', [string], $attrCollection)

                $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
                $paramDictionary.Add('DynamicParam', $dynParam)
                $paramDictionary
            }

            end {}
        }

        $expected = '[string] DynamicParam - Howdy partner'
        $Script = 'Test-Function -'
        $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-DynamicParam'
        $res.Count | Should -Be 1
        $res.CompletionText | Should -BeExactly '-DynamicParam'
        $res.ToolTip | Should -BeExactly $expected
    }

    It 'Should have type and name for parameter without help message' {
        Function Test-Function {
            param (
                [Parameter()]
                $WithParamAttribute,

                $WithoutParamAttribute
            )
        }

        $Script = 'Test-Function -'
        $res = (TabExpansion2 -inputScript $Script).CompletionMatches |
            Where-Object CompletionText -in '-WithParamAttribute', '-WithoutParamAttribute' |
            Sort-Object CompletionText
        $res.Count | Should -Be 2

        $res.CompletionText[0] | Should -BeExactly '-WithoutParamAttribute'
        $res.ToolTip[0] | Should -BeExactly '[Object] WithoutParamAttribute'

        $res.CompletionText[1] | Should -BeExactly '-WithParamAttribute'
        $res.ToolTip[1] | Should -BeExactly '[Object] WithParamAttribute'
    }

    It 'Should ignore errors when faling to get HelpMessage resource' {
        Function Test-Function {
            param (
                [Parameter(HelpMessageBaseName="invalid", HelpMessageResourceId="SomeId")]
                $InvalidHelpParam
            )
        }

        $expected = '[Object] InvalidHelpParam'
        $Script = 'Test-Function -InvalidHelpParam'
        $res = (TabExpansion2 -inputScript $Script).CompletionMatches
        $res.Count | Should -Be 1
        $res.CompletionText | Should -BeExactly '-InvalidHelpParam'
        $res.ToolTip | Should -BeExactly $expected
    }

    Context 'Start-Process -Verb parameter completion' {
        BeforeAll {
            function GetProcessInfoVerbs([string]$path, [switch]$singleQuote, [switch]$doubleQuote) {
                $verbs = (New-Object -TypeName System.Diagnostics.ProcessStartInfo -ArgumentList $path).Verbs

                if ($singleQuote) {
                    return ($verbs | ForEach-Object { "'$_'" })
                }
                elseif ($doubleQuote) {
                    return ($verbs | ForEach-Object { """$_""" })
                }

                return $verbs
            }

            $cmdPath = Join-Path -Path $TestDrive -ChildPath 'test.cmd'
            $cmdVerbs = GetProcessInfoVerbs -Path $cmdPath
            $cmdVerbsSingleQuote = GetProcessInfoVerbs -Path $cmdPath -SingleQuote
            $cmdVerbsDoubleQuote = GetProcessInfoVerbs -Path $cmdPath -DoubleQuote
            $exePath = Join-Path -Path $TestDrive -ChildPath 'test.exe'
            $exeVerbs = GetProcessInfoVerbs -Path $exePath
            $exeVerbsStartingWithRun = $exeVerbs | Where-Object { $_ -like 'run*' }
            $exeVerbsSingleQuote = GetProcessInfoVerbs -Path $exePath -SingleQuote
            $exeVerbsStartingWithRunSingleQuote = $exeVerbsSingleQuote | Where-Object { $_ -like "'run*" }
            $exeVerbsDoubleQuote = GetProcessInfoVerbs -Path $exePath -DoubleQuote
            $exeVerbsStartingWithRunDoubleQuote = $exeVerbsDoubleQuote | Where-Object { $_ -like """run*" }
            $powerShellExeWithNoExtension = 'powershell'
            $txtPath = Join-Path -Path $TestDrive -ChildPath 'test.txt'
            $txtVerbs = GetProcessInfoVerbs -Path $txtPath
            $wavPath = Join-Path -Path $TestDrive -ChildPath 'test.wav'
            $wavVerbs = GetProcessInfoVerbs -Path $wavPath
            $docxPath = Join-Path -Path $TestDrive -ChildPath 'test.docx'
            $docxVerbs = GetProcessInfoVerbs -Path $docxPath
            $fileWithNoExtensionPath = Join-Path -Path $TestDrive -ChildPath 'test'
            $fileWithNoExtensionVerbs = GetProcessInfoVerbs -Path $fileWithNoExtensionPath
        }

        It "Should complete Verb parameter for '<TextInput>'" -Skip:(!([System.Management.Automation.Platform]::IsWindowsDesktop)) -TestCases @(
            @{ TextInput = 'Start-Process -Verb '; ExpectedVerbs = '' }
            @{ TextInput = "Start-Process -FilePath $cmdPath -Verb "; ExpectedVerbs =  $cmdVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $cmdPath -Verb '"; ExpectedVerbs =  $cmdVerbsSingleQuote -join ' ' }
            @{ TextInput = "Start-Process -FilePath $cmdPath -Verb """; ExpectedVerbs =   $cmdVerbsDoubleQuote -join ' ' }
            @{ TextInput = "Start-Process -FilePath $exePath -Verb "; ExpectedVerbs = $exeVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $exePath -Verb run"; ExpectedVerbs = $exeVerbsStartingWithRun -join ' ' }
            @{ TextInput = "Start-Process -FilePath $exePath -Verb 'run"; ExpectedVerbs = $exeVerbsStartingWithRunSingleQuote -join ' ' }
            @{ TextInput = "Start-Process -FilePath $exePath -Verb ""run"; ExpectedVerbs = $exeVerbsStartingWithRunDoubleQuote -join ' ' }
            @{ TextInput = "Start-Process -FilePath $powerShellExeWithNoExtension -Verb "; ExpectedVerbs = $exeVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $txtPath -Verb "; ExpectedVerbs = $txtVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $wavPath -Verb "; ExpectedVerbs = $wavVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $docxPath -Verb "; ExpectedVerbs = $docxVerbs -join ' ' }
            @{ TextInput = "Start-Process -FilePath $fileWithNoExtensionPath -Verb "; ExpectedVerbs = $fileWithNoExtensionVerbs -join ' ' }
        ) {
            param($TextInput, $ExpectedVerbs)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText | Sort-Object
            $completionText -join ' ' | Should -BeExactly $ExpectedVerbs
        }
    }

    Context 'Scope parameter completion' {
        BeforeAll {
            $allScopes = 'Global Local Script'
            $allScopesSingleQuote = "'Global' 'Local' 'Script'"
            $allScopesDoubleQuote = """Global"" ""Local"" ""Script"""
            $globalScope = 'Global'
            $globalScopeSingleQuote = "'Global'"
            $globalScopeDoubleQuote = """Global"""
            $localScope = 'Local'
            $localScopeSingleQuote = "'Local'"
            $localScopeDoubleQuote = """Local"""
            $scriptScope = 'Script'
            $scriptScopeSingleQuote = "'Script'"
            $scriptScopeDoubleQuote = """Script"""
            $allScopeCommands = 'Clear-Variable', 'Export-Alias', 'Get-Alias', 'Get-PSDrive', 'Get-Variable', 'Import-Alias', 'New-Alias', 'New-PSDrive', 'New-Variable', 'Remove-Alias', 'Remove-PSDrive', 'Remove-Variable', 'Set-Alias', 'Set-Variable'
        }

        It "Should complete '<ParameterInput>' for '<Commands>'" -TestCases @(
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope "; ExpectedScopes = $allScopes }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope '"; ExpectedScopes = $allScopesSingleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope """; ExpectedScopes = $allScopesDoubleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope G"; ExpectedScopes = $globalScope }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'G"; ExpectedScopes = $globalScopeSingleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""G"; ExpectedScopes = $globalScopeDoubleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope Lo"; ExpectedScopes = $localScope }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'Lo"; ExpectedScopes = $localScopeSingleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""Lo"; ExpectedScopes = $localScopeDoubleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope Scr"; ExpectedScopes = $scriptScope }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'Scr"; ExpectedScopes = $scriptScopeSingleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""Scr"; ExpectedScopes = $scriptScopeDoubleQuote }
            @{ Commands = $allScopeCommands; ParameterInput = "-Scope NonExistentScope"; ExpectedScopes = '' }
        ) {
            param($Commands, $ParameterInput, $ExpectedScopes)
            foreach ($command in $Commands) {
                $joinedCommand = "$command $ParameterInput"
                $res = TabExpansion2 -inputScript $joinedCommand -cursorColumn $joinedCommand.Length
                $completionText = $res.CompletionMatches.CompletionText | Sort-Object
                $completionText -join ' ' | Should -BeExactly $ExpectedScopes
            }
        }
    }

    Context 'Get-Verb & Get-Command -Verb parameter completion' {
        BeforeAll {
            $allVerbs = 'Add Approve Assert Backup Block Build Checkpoint Clear Close Compare Complete Compress Confirm Connect Convert ConvertFrom ConvertTo Copy Debug Deny Deploy Disable Disconnect Dismount Edit Enable Enter Exit Expand Export Find Format Get Grant Group Hide Import Initialize Install Invoke Join Limit Lock Measure Merge Mount Move New Open Optimize Out Ping Pop Protect Publish Push Read Receive Redo Register Remove Rename Repair Request Reset Resize Resolve Restart Restore Resume Revoke Save Search Select Send Set Show Skip Split Start Step Stop Submit Suspend Switch Sync Test Trace Unblock Undo Uninstall Unlock Unprotect Unpublish Unregister Update Use Wait Watch Write'
            $allVerbsSingleQuote = "'Add' 'Approve' 'Assert' 'Backup' 'Block' 'Build' 'Checkpoint' 'Clear' 'Close' 'Compare' 'Complete' 'Compress' 'Confirm' 'Connect' 'Convert' 'ConvertFrom' 'ConvertTo' 'Copy' 'Debug' 'Deny' 'Deploy' 'Disable' 'Disconnect' 'Dismount' 'Edit' 'Enable' 'Enter' 'Exit' 'Expand' 'Export' 'Find' 'Format' 'Get' 'Grant' 'Group' 'Hide' 'Import' 'Initialize' 'Install' 'Invoke' 'Join' 'Limit' 'Lock' 'Measure' 'Merge' 'Mount' 'Move' 'New' 'Open' 'Optimize' 'Out' 'Ping' 'Pop' 'Protect' 'Publish' 'Push' 'Read' 'Receive' 'Redo' 'Register' 'Remove' 'Rename' 'Repair' 'Request' 'Reset' 'Resize' 'Resolve' 'Restart' 'Restore' 'Resume' 'Revoke' 'Save' 'Search' 'Select' 'Send' 'Set' 'Show' 'Skip' 'Split' 'Start' 'Step' 'Stop' 'Submit' 'Suspend' 'Switch' 'Sync' 'Test' 'Trace' 'Unblock' 'Undo' 'Uninstall' 'Unlock' 'Unprotect' 'Unpublish' 'Unregister' 'Update' 'Use' 'Wait' 'Watch' 'Write'"
            $allVerbsDoubleQuote = """Add"" ""Approve"" ""Assert"" ""Backup"" ""Block"" ""Build"" ""Checkpoint"" ""Clear"" ""Close"" ""Compare"" ""Complete"" ""Compress"" ""Confirm"" ""Connect"" ""Convert"" ""ConvertFrom"" ""ConvertTo"" ""Copy"" ""Debug"" ""Deny"" ""Deploy"" ""Disable"" ""Disconnect"" ""Dismount"" ""Edit"" ""Enable"" ""Enter"" ""Exit"" ""Expand"" ""Export"" ""Find"" ""Format"" ""Get"" ""Grant"" ""Group"" ""Hide"" ""Import"" ""Initialize"" ""Install"" ""Invoke"" ""Join"" ""Limit"" ""Lock"" ""Measure"" ""Merge"" ""Mount"" ""Move"" ""New"" ""Open"" ""Optimize"" ""Out"" ""Ping"" ""Pop"" ""Protect"" ""Publish"" ""Push"" ""Read"" ""Receive"" ""Redo"" ""Register"" ""Remove"" ""Rename"" ""Repair"" ""Request"" ""Reset"" ""Resize"" ""Resolve"" ""Restart"" ""Restore"" ""Resume"" ""Revoke"" ""Save"" ""Search"" ""Select"" ""Send"" ""Set"" ""Show"" ""Skip"" ""Split"" ""Start"" ""Step"" ""Stop"" ""Submit"" ""Suspend"" ""Switch"" ""Sync"" ""Test"" ""Trace"" ""Unblock"" ""Undo"" ""Uninstall"" ""Unlock"" ""Unprotect"" ""Unpublish"" ""Unregister"" ""Update"" ""Use"" ""Wait"" ""Watch"" ""Write"""
            $verbsStartingWithRe = 'Read Receive Redo Register Remove Rename Repair Request Reset Resize Resolve Restart Restore Resume Revoke'
            $verbsStartingWithEx = 'Exit Expand Export'
            $verbsStartingWithConv = 'Convert ConvertFrom ConvertTo'
            $lifeCycleVerbsStartingWithRe = 'Register Request Restart Resume'
            $lifeCycleVerbsStartingWithReSingleQuote = "'Register' 'Request' 'Restart' 'Resume'"
            $lifeCycleVerbsStartingWithReDoubleQuote = """Register"" ""Request"" ""Restart"" ""Resume"""
            $dataVerbsStartingwithEx = 'Expand Export'
            $lifeCycleAndCommmonVerbsStartingWithRe = 'Redo Register Remove Rename Request Reset Resize Restart Resume'
            $allLifeCycleAndCommonVerbs = 'Add Approve Assert Build Clear Close Complete Confirm Copy Deny Deploy Disable Enable Enter Exit Find Format Get Hide Install Invoke Join Lock Move New Open Optimize Pop Push Redo Register Remove Rename Request Reset Resize Restart Resume Search Select Set Show Skip Split Start Step Stop Submit Suspend Switch Undo Uninstall Unlock Unregister Wait Watch'
            $allJsonVerbs = 'ConvertFrom ConvertTo Test'
            $jsonVerbsStartingWithConv = 'ConvertFrom ConvertTo'
            $jsonVerbsStartingWithConvSingleQuote = "'ConvertFrom' 'ConvertTo'"
            $jsonVerbsStartingWithConvDoubleQuote = """ConvertFrom"" ""ConvertTo"""
            $allJsonAndJobVerbs = 'ConvertFrom ConvertTo Debug Get Receive Remove Start Stop Test Wait'
            $jsonAndJobVerbsStartingWithSt = 'Start Stop'
            $allObjectVerbs = 'Compare ForEach Group Measure New Select Sort Tee Where'
            $utilityModuleObjectVerbs = 'Compare Group Measure New Select Sort Tee'
            $utilityModuleObjectVerbsStartingWithS = 'Select Sort'
            $utilityModuleObjectVerbsStartingWithSSingleQuote = "'Select' 'Sort'"
            $utilityModuleObjectVerbsStartingWithSDoubleQuote = """Select"" ""Sort"""
            $utilityModuleObjectVerbsStartingWithS
            $coreModuleObjectVerbs = 'ForEach Where'
        }

        It "Should complete Verb parameter for '<TextInput>'" -TestCases @(
            @{ TextInput = 'Get-Verb -Verb '; ExpectedVerbs = $allVerbs }
            @{ TextInput = "Get-Verb -Verb '"; ExpectedVerbs = $allVerbsSingleQuote }
            @{ TextInput = "Get-Verb -Verb """; ExpectedVerbs = $allVerbsDoubleQuote }
            @{ TextInput = 'Get-Verb -Group Lifecycle, Common -Verb '; ExpectedVerbs = $allLifeCycleAndCommonVerbs }
            @{ TextInput = 'Get-Verb -Verb Re'; ExpectedVerbs = $verbsStartingWithRe }
            @{ TextInput = 'Get-Verb -Group Lifecycle -Verb Re'; ExpectedVerbs = $lifeCycleVerbsStartingWithRe }
            @{ TextInput = "Get-Verb -Group Lifecycle -Verb 'Re"; ExpectedVerbs = $lifeCycleVerbsStartingWithReSingleQuote }
            @{ TextInput = "Get-Verb -Group Lifecycle -Verb ""Re"; ExpectedVerbs = $lifeCycleVerbsStartingWithReDoubleQuote }
            @{ TextInput = 'Get-Verb -Group Lifecycle -Verb Re'; ExpectedVerbs = $lifeCycleVerbsStartingWithRe }
            @{ TextInput = 'Get-Verb -Group Lifecycle, Common -Verb Re'; ExpectedVerbs = $lifeCycleAndCommmonVerbsStartingWithRe }
            @{ TextInput = 'Get-Verb -Verb Ex'; ExpectedVerbs = $verbsStartingWithEx }
            @{ TextInput = 'Get-Verb -Group Data -Verb Ex'; ExpectedVerbs = $dataVerbsStartingwithEx }
            @{ TextInput = 'Get-Verb -Group NonExistentGroup -Verb '; ExpectedVerbs = '' }
            @{ TextInput = 'Get-Verb -Verb Conv'; ExpectedVerbs = $verbsStartingWithConv }
            @{ TextInput = 'Get-Command -Verb '; ExpectedVerbs = $allVerbs }
            @{ TextInput = 'Get-Command -Verb Re'; ExpectedVerbs = $verbsStartingWithRe }
            @{ TextInput = 'Get-Command -Verb Ex'; ExpectedVerbs = $verbsStartingWithEx }
            @{ TextInput = 'Get-Command -Verb Conv'; ExpectedVerbs = $verbsStartingWithConv }
            @{ TextInput = 'Get-Command -Noun Json -Verb '; ExpectedVerbs = $allJsonVerbs }
            @{ TextInput = 'Get-Command -Noun Json -Verb Conv'; ExpectedVerbs = $jsonVerbsStartingWithConv }
            @{ TextInput = "Get-Command -Noun Json -Verb 'Conv"; ExpectedVerbs = $jsonVerbsStartingWithConvSingleQuote }
            @{ TextInput = "Get-Command -Noun Json -Verb ""Conv"; ExpectedVerbs = $jsonVerbsStartingWithConvDoubleQuote }
            @{ TextInput = 'Get-Command -Noun Json, Job -Verb '; ExpectedVerbs = $allJsonAndJobVerbs }
            @{ TextInput = 'Get-Command -Noun Json, Job -Verb St'; ExpectedVerbs = $jsonAndJobVerbsStartingWithSt }
            @{ TextInput = 'Get-Command -Noun NonExistentNoun -Verb '; ExpectedVerbs = '' }
            @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility,Microsoft.PowerShell.Core -Verb '; ExpectedVerbs = $allObjectVerbs }
            @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb '; ExpectedVerbs = $utilityModuleObjectVerbs }
            @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb S'; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithS }
            @{ TextInput = "Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb 'S"; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithSSingleQuote }
            @{ TextInput = "Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb ""S"; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithSDoubleQuote }
            @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Core -Verb '; ExpectedVerbs = $coreModuleObjectVerbs }
        ) {
            param($TextInput, $ExpectedVerbs)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText | Sort-Object
            $completionText -join ' ' | Should -BeExactly $ExpectedVerbs
        }
    }

    Context 'StrictMode Version parameter completion' {
        BeforeAll {
            $allStrictModeVersions = '1.0 2.0 3.0 Latest'
            $allStrictModeVersionsSingleQuote = "'1.0' '2.0' '3.0' 'Latest'"
            $allStrictModeVersionsDoubleQuote = """1.0"" ""2.0"" ""3.0"" ""Latest"""
            $versionOne = '1.0'
            $versionTwo = '2.0'
            $versionThree = '3.0'
            $latestVersion = 'Latest'
            $latestVersionSingleQuote = "'Latest'"
            $latestVersionDoubleQuote = """Latest"""
        }

        It "Should complete Version for '<TextInput>'" -TestCases @(
            @{ TextInput = "Set-StrictMode -Version "; ExpectedVersions = $allStrictModeVersions }
            @{ TextInput = "Set-StrictMode -Version '"; ExpectedVersions = $allStrictModeVersionsSingleQuote }
            @{ TextInput = "Set-StrictMode -Version """; ExpectedVersions = $allStrictModeVersionsDoubleQuote }
            @{ TextInput = "Set-StrictMode -Version 1"; ExpectedVersions = $versionOne }
            @{ TextInput = "Set-StrictMode -Version 2"; ExpectedVersions = $versionTwo }
            @{ TextInput = "Set-StrictMode -Version 3"; ExpectedVersions = $versionThree }
            @{ TextInput = "Set-StrictMode -Version Lat"; ExpectedVersions = $latestVersion }
            @{ TextInput = "Set-StrictMode -Version 'Lat"; ExpectedVersions = $latestVersionSingleQuote }
            @{ TextInput = "Set-StrictMode -Version ""Lat"; ExpectedVersions = $latestVersionDoubleQuote }
            @{ TextInput = "Set-StrictMode -Version NonExistentVersion"; ExpectedVersions = '' }
        ) {
            param($TextInput, $ExpectedVersions)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText | Sort-Object
            $completionText -join ' ' | Should -BeExactly $ExpectedVersions
        }
    }

    Context 'Help Module parameter completion' {
        BeforeAll {
            $utilityModule = 'Microsoft.PowerShell.Utility'
            $managementModule = 'Microsoft.PowerShell.Management'
            $allMicrosoftPowerShellModules = (Get-Module -Name Microsoft.PowerShell* -ListAvailable).Name
            Import-Module -Name $allMicrosoftPowerShellModules -ErrorAction SilentlyContinue
            $allMicrosoftPowerShellModules = ($allMicrosoftPowerShellModules | Sort-Object -Unique) -join ' '
        }

        It "Should complete Module for '<TextInput>'" -TestCases @(
            @{ TextInput = "Save-Help -Module Microsoft.PowerShell.U"; ExpectedModules = $utilityModule }
            @{ TextInput = "Update-Help -Module Microsoft.PowerShell.U"; ExpectedModules = $utilityModule }
            @{ TextInput = "Save-Help -Module Microsoft.PowerShell.Man"; ExpectedModules = $managementModule }
            @{ TextInput = "Update-Help -Module Microsoft.PowerShell.Man"; ExpectedModules = $managementModule }
            @{ TextInput = "Save-Help -Module Microsoft.Powershell"; ExpectedModules = $allMicrosoftPowerShellModules }
            @{ TextInput = "Update-Help -Module Microsoft.PowerShell"; ExpectedModules = $allMicrosoftPowerShellModules }
            @{ TextInput = "Save-Help -Module NonExistentModulePrefix"; ExpectedModules = '' }
            @{ TextInput = "Update-Help -Module NonExistentModulePrefix"; ExpectedModules = '' }
        ) {
            param($TextInput, $ExpectedModules)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText | Sort-Object -Unique
            $completionText -join ' ' | Should -BeExactly $ExpectedModules
        }
    }

    Context 'New-ItemProperty -PropertyType parameter completion' {
        BeforeAll {
            if ($IsWindows) {
                $allRegistryValueKinds = 'String ExpandString Binary DWord MultiString QWord Unknown'
                $allRegistryValueKindsWithQuotes = "'String' 'ExpandString' 'Binary' 'DWord' 'MultiString' 'QWord' 'Unknown'"
                $dwordValueKind = 'DWord'
                $qwordValueKind = 'QWord'
                $binaryValueKind = 'Binary'
                $multiStringValueKind = 'MultiString'
                $registryPath = "HKCU:\test1\sub"
                New-Item -Path $registryPath -Force
                $registryLiteralPath = "HKCU:\test2\*\sub"
                New-Item -Path $registryLiteralPath -Force
                $fileSystemPath = "TestDrive:\test1.txt"
                New-Item -Path $fileSystemPath -Force
                $fileSystemLiteralPathDir = "TestDrive:\[]"
                $fileSystemLiteralPath = "$fileSystemLiteralPathDir\test2.txt"
                New-Item -Path $fileSystemLiteralPath -Force
            }
        }

        It "Should complete Property Type for '<TextInput>'" -Skip:(!$IsWindows) -TestCases @(
            # -Path completions
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType "; ExpectedPropertyTypes = $allRegistryValueKinds }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType d"; ExpectedPropertyTypes = $dwordValueKind }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType q"; ExpectedPropertyTypes = $qwordValueKind }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType bin"; ExpectedPropertyTypes = $binaryValueKind }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType multi"; ExpectedPropertyTypes = $multiStringValueKind }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType invalidproptype"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -Path $fileSystemPath -PropertyType "; ExpectedPropertyTypes = '' }

            # -LiteralPath completions
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType "; ExpectedPropertyTypes = $allRegistryValueKinds }
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType d"; ExpectedPropertyTypes = $dwordValueKind }
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType q"; ExpectedPropertyTypes = $qwordValueKind }
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType bin"; ExpectedPropertyTypes = $binaryValueKind }
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType multi"; ExpectedPropertyTypes = $multiStringValueKind }
            @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType invalidproptype"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -LiteralPath $fileSystemLiteralPath -PropertyType "; ExpectedPropertyTypes = '' }

            # All of these should return no completion since they don't specify -Path/-LiteralPath
            @{ TextInput = "New-ItemProperty -PropertyType "; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -PropertyType d"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -PropertyType q"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -PropertyType bin"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -PropertyType multi"; ExpectedPropertyTypes = '' }
            @{ TextInput = "New-ItemProperty -PropertyType invalidproptype"; ExpectedPropertyTypes = '' }

            # All of these should return completion even with quotes included
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType '"; ExpectedPropertyTypes = $allRegistryValueKindsWithQuotes }
            @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType 'bin"; ExpectedPropertyTypes = "'$binaryValueKind'" }
        ) {
            param($TextInput, $ExpectedPropertyTypes)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly $ExpectedPropertyTypes

            foreach ($match in $res.CompletionMatches) {
                $completionText = $match.CompletionText.Replace("""", "").Replace("'", "")
                $listItemText = $match.ListItemText
                $completionText | Should -BeExactly $listItemText
                $match.ToolTip | Should -Not -BeNullOrEmpty
            }
        }

        It "Test fallback to provider of current location if no path specified" -Skip:(!$IsWindows) {
            try {
                Push-Location HKCU:\
                $textInput = "New-ItemProperty -PropertyType "
                $res = TabExpansion2 -inputScript $textInput -cursorColumn $textInput.Length
                $completionText = $res.CompletionMatches.CompletionText
                $completionText -join ' ' | Should -BeExactly $allRegistryValueKinds
            }
            finally {
                Pop-Location
            }
        }

        AfterAll {
            if ($IsWindows) {
                Remove-Item -Path $registryPath -Force
                Remove-Item -LiteralPath $registryLiteralPath -Force
                Remove-Item -Path $fileSystemPath -Force
                Remove-Item -LiteralPath $fileSystemLiteralPathDir -Recurse -Force
            }
        }
    }

    Context 'Get-Command -Noun parameter completion' {
        BeforeAll {
            function GetModuleCommandNouns(
                [string]$Module,
                [string]$Verb,
                [switch]$SingleQuote,
                [switch]$DoubleQuote)
            {

                $commandParams = @{}

                if ($PSBoundParameters.ContainsKey('Module')) {
                    $commandParams['Module'] = $Module
                }

                if ($PSBoundParameters.ContainsKey('Verb')) {
                    $commandParams['Verb'] = $Verb
                }

                $nouns = (Get-Command @commandParams).Noun

                if ($SingleQuote) {
                    return ($nouns | ForEach-Object { "'$_'" })
                }
                elseif ($DoubleQuote) {
                    return ($nouns | ForEach-Object { """$_""" })
                }

                return $nouns
            }

            $utilityModuleName = 'Microsoft.PowerShell.Utility'

            $allUtilityCommandNouns = GetModuleCommandNouns -Module $utilityModuleName
            $allUtilityCommandNounsSingleQuote = GetModuleCommandNouns -Module $utilityModuleName -SingleQuote
            $allUtilityCommandNounsDoubleQuote = GetModuleCommandNouns -Module $utilityModuleName -DoubleQuote
            $utilityCommandNounsStartingWithF = $allUtilityCommandNouns | Where-Object { $_ -like 'F*'}
            $utilityCommandNounsStartingWithFSingleQuote = $allUtilityCommandNounsSingleQuote | Where-Object { $_ -like "'F*"}
            $utilityCommandNounsStartingWithFDoubleQuote = $allUtilityCommandNounsDoubleQuote | Where-Object { $_ -like """F*"}

            $allUtilityCommandNounsWithConvertToVerb = GetModuleCommandNouns -Module $utilityModuleName -Verb 'ConvertTo'
            $allUtilityCommandNounsWithConvertToVerbSingleQuote = GetModuleCommandNouns -Module $utilityModuleName -SingleQuote -Verb 'ConvertTo'
            $allUtilityCommandNounsWithConvertToVerbDoubleQuote = GetModuleCommandNouns -Module $utilityModuleName -DoubleQuote -Verb 'ConvertTo'
            $utilityCommandNounsWithConvertToVerb = $allUtilityCommandNounsWithConvertToVerb | Where-Object { $_ -in 'CliXml', 'Csv', 'Html', 'Json', 'Xml' }
            $utilityCommandNounsWithConvertToVerbSingleQuote = $allUtilityCommandNounsWithConvertToVerbSingleQuote | Where-Object { $_ -in "'CliXml'", "'Csv'", "'Html'", "'Json'", "'Xml'" }
            $utilityCommandNounsWithConvertToVerbDoubleQuote = $allUtilityCommandNounsWithConvertToVerbDoubleQuote | Where-Object { $_ -in """CliXml""", """Csv""", """Html""", """Json""", """Xml""" }
            $utilityCommandNounsWithConvertToVerbStartingWithC = $allUtilityCommandNounsWithConvertToVerb | Where-Object { $_ -in 'CliXml', 'Csv' }
            $utilityCommandNounsWithConvertToVerbStartingWithCSingleQuote = $allUtilityCommandNounsWithConvertToVerbSingleQuote | Where-Object { $_ -in "'CliXml'", "'Csv'" }
            $utilityCommandNounsWithConvertToVerbStartingWithCDoubleQuote = $allUtilityCommandNounsWithConvertToVerbDoubleQuote | Where-Object { $_ -in """CliXml""", """Csv""" }
        }

        It "Should complete Noun for '<TextInput>'" -TestCases @(
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun "; ExpectedNouns = $allUtilityCommandNouns }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun '"; ExpectedNouns = $allUtilityCommandNounsSingleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun """; ExpectedNouns = $allUtilityCommandNounsDoubleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun F"; ExpectedNouns = $utilityCommandNounsStartingWithF  }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun 'F"; ExpectedNouns = $utilityCommandNounsStartingWithFSingleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Noun ""F"; ExpectedNouns = $utilityCommandNounsStartingWithFDoubleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun "; ExpectedNouns = $utilityCommandNounsWithConvertToVerb  }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun '"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbSingleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun """; ExpectedNouns = $utilityCommandNounsWithConvertToVerbDoubleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithC  }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun 'C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithCSingleQuote }
            @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun ""C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithCDoubleQuote }
        ) {
            param($TextInput, $ExpectedNouns)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText

            # Avoid using Sort-Object -Unique because it generates different order than SortedSet on MacOS/Linux
            $sortedSetExpectedNouns = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
            foreach ($noun in $ExpectedNouns)
            {
                $sortedSetExpectedNouns.Add($noun) | Out-Null
            }

            $completionText -join ' ' | Should -BeExactly ($sortedSetExpectedNouns -join ' ')
        }
    }

    Context "Get-ExperimentalFeature -Name parameter completion" {
        BeforeAll {
            function GetExperimentalFeatureNames([switch]$SingleQuote, [switch]$DoubleQuote) {
                $features = (Get-ExperimentalFeature).Name

                if ($SingleQuote) {
                    return ($features | ForEach-Object { "'$_'" })
                }
                elseif ($DoubleQuote) {
                    return ($features | ForEach-Object { """$_""" })
                }

                return $features
            }

            $allExperimentalFeatures = GetExperimentalFeatureNames
            $allExperimentalFeaturesSingleQuote = GetExperimentalFeatureNames -SingleQuote
            $allExperimentalFeaturesDoubleQuote = GetExperimentalFeatureNames -DoubleQuote
            $experimentalFeaturesStartingWithPS = $allExperimentalFeatures | Where-Object { $_ -like 'PS*'}
            $experimentalFeaturesStartingWithPSSingleQuote = $allExperimentalFeaturesSingleQuote | Where-Object { $_ -like "'PS*" }
            $experimentalFeaturesStartingWithPSDoubleQuote = $allExperimentalFeaturesDoubleQuote | Where-Object { $_ -like """PS*" }
        }

        It "Should complete Name for '<TextInput>'" -TestCases @(
            @{ TextInput = "Get-ExperimentalFeature -Name "; ExpectedExperimentalFeatureNames = $allExperimentalFeatures }
            @{ TextInput = "Get-ExperimentalFeature -Name '"; ExpectedExperimentalFeatureNames = $allExperimentalFeaturesSingleQuote }
            @{ TextInput = "Get-ExperimentalFeature -Name """; ExpectedExperimentalFeatureNames = $allExperimentalFeaturesDoubleQuote }
            @{ TextInput = "Get-ExperimentalFeature -Name PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPS }
            @{ TextInput = "Get-ExperimentalFeature -Name 'PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPSSingleQuote }
            @{ TextInput = "Get-ExperimentalFeature -Name ""PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPSDoubleQuote }
        ) {
            param($TextInput, $ExpectedExperimentalFeatureNames)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly (($ExpectedExperimentalFeatureNames | Sort-Object -Unique) -join ' ')
        }
    }

    Context "Join-String -Separator & -FormatString parameter completion" {
        BeforeAll {
            if ($IsWindows) {
                $allSeparators = "',' ', ' ';' '; ' ""``r``n"" '-' ' '"
                $allFormatStrings = "'[{0}]' '{0:N2}' ""``r``n    ```${0}"" ""``r``n    [string] ```${0}"""
                $newlineSeparator = """``r``n"""
                $newlineFormatStrings = """``r``n    ```${0}"" ""``r``n    [string] ```${0}"""
            }
            else {
                $allSeparators = "',' ', ' ';' '; ' ""``n"" '-' ' '"
                $allFormatStrings = "'[{0}]' '{0:N2}' ""``n    ```${0}"" ""``n    [string] ```${0}"""
                $newlineSeparator = """``n"""
                $newlineFormatStrings = """``n    ```${0}"" ""``n    [string] ```${0}"""
            }

            $commaSeparators = "',' ', '"
            $semiColonSeparators = "';' '; '"
            
            $squareBracketFormatString = "'[{0}]'"
            $curlyBraceFormatString = "'{0:N2}'"
        }

        It "Should complete for '<TextInput>'" -TestCases @(
            @{ TextInput = "Join-String -Separator "; Expected = $allSeparators }
            @{ TextInput = "Join-String -Separator '"; Expected = $allSeparators }
            @{ TextInput = "Join-String -Separator """; Expected = $allSeparators.Replace("'", """") }
            @{ TextInput = "Join-String -Separator ',"; Expected = $commaSeparators }
            @{ TextInput = "Join-String -Separator "","; Expected = $commaSeparators.Replace("'", """") }
            @{ TextInput = "Join-String -Separator ';"; Expected = $semiColonSeparators }
            @{ TextInput = "Join-String -Separator "";"; Expected = $semiColonSeparators.Replace("'", """") }
            @{ TextInput = "Join-String -FormatString "; Expected = $allFormatStrings }
            @{ TextInput = "Join-String -FormatString '"; Expected = $allFormatStrings }
            @{ TextInput = "Join-String -FormatString """; Expected = $allFormatStrings.Replace("'", """") }
            @{ TextInput = "Join-String -FormatString ["; Expected = $squareBracketFormatString }
            @{ TextInput = "Join-String -FormatString '["; Expected = $squareBracketFormatString }
            @{ TextInput = "Join-String -FormatString ""["; Expected = $squareBracketFormatString.Replace("'", """") }
            @{ TextInput = "Join-String -FormatString '{"; Expected = $curlyBraceFormatString }
            @{ TextInput = "Join-String -FormatString ""{"; Expected = $curlyBraceFormatString.Replace("'", """") }
        ) {
            param($TextInput, $Expected)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly $Expected

            foreach ($match in $res.CompletionMatches) {
                $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "")
                $completionText = $match.CompletionText.Replace("""", "").Replace("'", "")
                $listItemText = $match.ListItemText
                $toolTip.StartsWith($completionText) | Should -BeTrue
                $toolTip.EndsWith($listItemText) | Should -BeTrue
            }
        }

        It "Should complete for '<TextInput>'" -Skip:(!$IsWindows) -TestCases @(
            @{ TextInput = "Join-String -Separator '``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator ""``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator '``r"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator ""``r"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator '``r``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator ""``r``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -FormatString '``"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString ""``"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString '``r"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString ""``r"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString '``r``"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString ""``r``"; Expected = $newlineFormatStrings }
        ) {
            param($TextInput, $Expected)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly $Expected

            foreach ($match in $res.CompletionMatches) {
                $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "")
                $completionText = $match.CompletionText.Replace("""", "").Replace("'", "")
                $listItemText = $match.ListItemText
                $toolTip.StartsWith($completionText) | Should -BeTrue
                $toolTip.EndsWith($listItemText) | Should -BeTrue
            }
        }

        It "Should complete for '<TextInput>'" -Skip:($IsWindows) -TestCases @(
            @{ TextInput = "Join-String -Separator '``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator ""``"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator '``n"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -Separator ""``n"; Expected = $newlineSeparator }
            @{ TextInput = "Join-String -FormatString '``"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString ""``"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString '``n"; Expected = $newlineFormatStrings }
            @{ TextInput = "Join-String -FormatString ""``n"; Expected = $newlineFormatStrings }
        ) {
            param($TextInput, $Expected)
            $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly $Expected

            foreach ($match in $res.CompletionMatches) {
                $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "")
                $completionText = $match.CompletionText.Replace("""", "").Replace("'", "")
                $listItemText = $match.ListItemText
                $toolTip.StartsWith($completionText) | Should -BeTrue
                $toolTip.EndsWith($listItemText) | Should -BeTrue
            }
        }
    }

    Context "Format cmdlet's View paramter completion" {
        BeforeAll {
            $viewDefinition = @'
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
  <ViewDefinitions>
    <View>
      <Name>R A M</Name>
      <ViewSelectedBy>
        <TypeName>System.Diagnostics.Process</TypeName>
      </ViewSelectedBy>
      <TableControl>
        <TableHeaders>
          <TableColumnHeader>
            <Label>ProcName</Label>
            <Width>40</Width>
            <Alignment>Center</Alignment>
          </TableColumnHeader>
          <TableColumnHeader>
            <Label>PagedMem</Label>
            <Width>40</Width>
            <Alignment>Center</Alignment>
          </TableColumnHeader>
          <TableColumnHeader>
            <Label>PeakWS</Label>
            <Width>40</Width>
            <Alignment>Center</Alignment>
          </TableColumnHeader>
        </TableHeaders>
        <TableRowEntries>
          <TableRowEntry>
            <TableColumnItems>
              <TableColumnItem>
                <Alignment>Center</Alignment>
                <PropertyName>Name</PropertyName>
              </TableColumnItem>
              <TableColumnItem>
                <Alignment>Center</Alignment>
                <PropertyName>PagedMemorySize</PropertyName>
              </TableColumnItem>
              <TableColumnItem>
                <Alignment>Center</Alignment>
                <PropertyName>PeakWorkingSet</PropertyName>
              </TableColumnItem>
            </TableColumnItems>
          </TableRowEntry>
        </TableRowEntries>
      </TableControl>
    </View>
  </ViewDefinitions>
</Configuration>
'@

            $tempViewFile = Join-Path -Path $TestDrive -ChildPath 'processViewDefinition.ps1xml'
            Set-Content -LiteralPath $tempViewFile -Value $viewDefinition -Force

            $ps = [PowerShell]::Create()
            $null = $ps.AddScript("Update-FormatData -AppendPath $tempViewFile")
            $ps.Invoke()
            $ps.HadErrors | Should -BeFalse
            $ps.Commands.Clear()

            Remove-Item -LiteralPath $tempViewFile -Force -ErrorAction SilentlyContinue
        }

        It 'Should complete Get-ChildItem | <cmd> -View' -TestCases (
            @{ cmd = 'Format-Table'; expected = "children childrenWithHardlink$(if (!$IsWindows) { ' childrenWithUnixStat' })" },
            @{ cmd = 'Format-List'; expected = 'children' },
            @{ cmd = 'Format-Wide'; expected = 'children' },
            @{ cmd = 'Format-Custom'; expected = '' }
        ) {
            param($cmd, $expected)

            # The completion is based on OutputTypeAttribute() of the cmdlet.
            $res = TabExpansion2 -inputScript "Get-ChildItem | $cmd -View " -cursorColumn "Get-ChildItem | $cmd -View ".Length
            $completionText = $res.CompletionMatches.CompletionText | Sort-Object
            $completionText -join ' ' | Should -BeExactly $expected
        }

        It 'Should complete $processList = Get-Process; $processList | <cmd>' -TestCases (
            @{ cmd = 'Format-Table -View '; expected = "'R A M'", "Priority", "process", "ProcessModule", "ProcessWithUserName", "StartTime" },
            @{ cmd = 'Format-List -View '; expected = '' },
            @{ cmd = 'Format-Wide -View '; expected = 'process' },
            @{ cmd = 'Format-Custom -View '; expected = '' },
            @{ cmd = 'Format-Table -View S'; expected = "StartTime" },
            @{ cmd = "Format-Table -View 'S"; expected = "'StartTime'" },
            @{ cmd = "Format-Table -View R"; expected = "'R A M'" }
        ) {
            param($cmd, $expected)

            $null = $ps.AddScript({
                param ($cmd)
                $processList = Get-Process
                $res = TabExpansion2 -inputScript "`$processList | $cmd" -cursorColumn "`$processList | $cmd".Length
                $completionText = $res.CompletionMatches.CompletionText | Sort-Object
                $completionText
            }).AddArgument($cmd)

            $result = $ps.Invoke()
            $ps.Commands.Clear()
            $expected = ($expected | Sort-Object) -join ' '
            $result -join ' ' | Should -BeExactly $expected
        }
    }

    Context NativeCommand {
        BeforeAll {
            ## Find a native command that is not 'pwsh'. We will use 'pwsh' for fallback completer tests later.
            $nativeCommand = Get-Command -CommandType Application -TotalCount 2 |
                Where-Object Name -NotLike pwsh* |
                Select-Object -First 1
        }

        It 'Completes native commands with -' {
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '-') {
                    return "-flag"
                }
                else {
                    return "unexpected wordtocomplete"
                }
            }
            $line = "$nativeCommand -"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "-flag"
        }

        It 'Completes native commands with --' {
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '--') {
                    return "--flag"
                }
                else {
                    return "unexpected wordtocomplete"
                }
            }
            $line = "$nativeCommand --"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "--flag"
        }

        It 'Completes native commands with --f' {
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '--f') {
                    return "--flag"
                }
                else {
                    return "unexpected wordtocomplete"
                }
            }
            $line = "$nativeCommand --f"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "--flag"
        }

        It 'Completes native commands with -o' {
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '-o') {
                    return "-option"
                }
                else {
                    return "unexpected wordtocomplete"
                }
            }
            $line = "$nativeCommand -o"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "-option"
        }

        It 'Covers an arbitrary unbound native command with -t' {
            ## Register a completer for $nativeCommand.
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '-t') {
                    return "-terminal"
                }
            }

            ## Register a fallback native command completer.
            Register-ArgumentCompleter -NativeFallback -ScriptBlock {
                param($wordToComplete, $ast, $cursorColumn)
                if ($wordToComplete -eq '-t') {
                    return "-testing"
                }
            }

            ## The specific completer will be used if it exists.
            $line = "$nativeCommand -t"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "-terminal"

            ## Otherwise, the fallback completer will kick in.
            $line = "pwsh -t"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "-testing"

            ## Remove the completer for $nativeCommand.
            Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock $null

            ## The fallback completer will be used for $nativeCommand.
            $line = "$nativeCommand -t"
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches.CompletionText | Should -BeExactly "-testing"

            ## Remove the fallback completer for $nativeCommand.
            Register-ArgumentCompleter -NativeFallback -ScriptBlock $null

            ## The fallback completer will be used for $nativeCommand.
            $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length
            $res.CompletionMatches | Should -HaveCount 0
        }
    }

    It 'Should complete "Export-Counter -FileFormat" with available output formats' -Pending {
        $res = TabExpansion2 -inputScript 'Export-Counter -FileFormat ' -cursorColumn 'Export-Counter -FileFormat '.Length
        $res.CompletionMatches | Should -HaveCount 3
        $completionText = $res.CompletionMatches.CompletionText | Sort-Object
        $completionText -join ' ' | Should -BeExactly 'blg csv tsv'
    }

    it 'Should include positionally bound parameters when completing in front of parameter value' {
        $TestString = 'Get-ChildItem -^ $HOME'
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
        $res.CompletionMatches.CompletionText | Should -Contain "-Path"
    }

    it 'Should find the closest positional parameter match' {
        $TestString = @'
function Verb-Noun
{
    Param
    (
        [Parameter(Position = 0)]
        [string]
        $Param1,
        [Parameter(Position = 1)]
        [System.Management.Automation.ActionPreference]
        $Param2
    )
}
Verb-Noun -Param1 Hello ^
'@
        $CursorIndex = $TestString.IndexOf('^')
        $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex
        $res.CompletionMatches[0].CompletionText | Should -Be "Break"
    }

    it 'Should complete command with an empty arrayexpression element' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem @()' -cursorColumn 1
        $res.CompletionMatches[0].CompletionText | Should -Be "Get-ChildItem"
    }

    it 'Should not complete TabExpansion2 variables' {
        $res = TabExpansion2 -inputScript '$' -cursorColumn 1
        $res.CompletionMatches.CompletionText | Should -Not -Contain '$positionOfCursor'
    }

    it 'Should prefer the default parameterset when completing positional parameters' {
        $ScriptInput = 'Get-ChildItem | Where-Object '
        $res = TabExpansion2 -inputScript $ScriptInput -cursorColumn $ScriptInput.Length
        $res.CompletionMatches[0].CompletionText | Should -Be "Attributes"
    }

    it 'Should complete base class members of types without type definition AST' {
        $res = TabExpansion2 -inputScript @'
class InheritedClassTest : System.Attribute
{
    [void] TestMethod()
    {
        $this.
'@
        $res.CompletionMatches.CompletionText | Should -Contain 'TypeId'
    }

    it 'Should not complete parameter aliases if the real parameter is in the completion results' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem -p'
        $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga'
        $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction'
    }

    it 'Should not complete parameter aliases if the real parameter is in the completion results (Non ambiguous parameters)' {
        $res = TabExpansion2 -inputScript 'Get-ChildItem -prog'
        $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga'
        $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction'
    }

    It 'Should complete dynamic parameters with partial input' {
        # See issue: #19498
        try
        {
            Push-Location function:
            $res = TabExpansion2 -inputScript 'Get-ChildItem -LiteralPath $PSHOME -Fi'
            $res.CompletionMatches[1].CompletionText | Should -Be '-File'
        }
        finally
        {
            Pop-Location
        }
    }
    it 'Should complete enum class members for Enums in script text' {
        $res = TabExpansion2 -inputScript 'enum Test1 {Val1};([Test1]"").'
        $res.CompletionMatches.CompletionText[0] | Should -Be 'value__'
        $res.CompletionMatches.CompletionText | Should -Contain 'HasFlag('
    }

    Context "Script name completion" {
        BeforeAll {
            Setup -f 'install-powershell.ps1' -Content ""
            Setup -f 'remove-powershell.ps1' -Content ""

            $scriptWithWildcardCases = @(
                @{
                    command = '.\install-*.ps1'
                    expectedCommand = Join-Path -Path '.' -ChildPath 'install-powershell.ps1'
                    name = "'$(Join-Path -Path '.' -ChildPath 'install-powershell.ps1')'"
                }
                @{
                    command = (Join-Path ${TestDrive}  -ChildPath 'install-*.ps1')
                    expectedCommand = (Join-Path ${TestDrive}  -ChildPath 'install-powershell.ps1')
                    name = "'$(Join-Path -Path '.' -ChildPath 'install-powershell.ps1')' by fully qualified path"
                }
                @{
                    command = '.\?emove-powershell.ps1'
                    expectedCommand = Join-Path -Path '.' -ChildPath 'remove-powershell.ps1'
                    name = "'$(Join-Path -Path '.' -ChildPath '?emove-powershell.ps1')'"
                }
                @{
                    # [] cause the parser to create a new token.
                    # So, the command must be quoted to tab complete.
                    command = "'.\[ra]emove-powershell.ps1'"
                    expectedCommand = "'$(Join-Path -Path '.' -ChildPath 'remove-powershell.ps1')'"
                    name = "'$(Join-Path -Path '.' -ChildPath '[ra]emove-powershell.ps1')'"
                }
            )

            Push-Location ${TestDrive}\
        }

        AfterAll {
            Pop-Location
        }

        It "Input <name> should successfully complete" -TestCases $scriptWithWildcardCases {
            param($command, $expectedCommand)
            $res = TabExpansion2 -inputScript $command -cursorColumn $command.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expectedCommand
        }
    }

    Context "Script parameter completion" {
        BeforeAll {
            Setup -File -Path 'ModuleReqTest.ps1' -Content @'
#requires -Modules ThisModuleDoesNotExist
param ($Param1)
'@
            Setup -File -Path 'AdminReqTest.ps1' -Content @'
#requires -RunAsAdministrator
param ($Param1)
'@
            Push-Location ${TestDrive}\
        }

        AfterAll {
            Pop-Location
        }

        It "Input should successfully complete script parameter for script with failed script requirements" {
            $res = TabExpansion2 -inputScript '.\ModuleReqTest.ps1 -'
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1'
        }

        It "Input should successfully complete script parameter for admin script while not elevated" {
            $res = TabExpansion2 -inputScript '.\AdminReqTest.ps1 -'
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1'
        }
    }

    Context "File name completion" {
        BeforeAll {
            $tempDir = Join-Path -Path $TestDrive -ChildPath "baseDir"
            $oneSubDir = Join-Path -Path $tempDir -ChildPath "oneSubDir"
            $oneSubDirPrime = Join-Path -Path $tempDir -ChildPath "prime"
            $twoSubDir = Join-Path -Path $oneSubDir -ChildPath "twoSubDir"
            $caseTestPath = Join-Path $testdrive "CaseTest"

            New-Item -Path $tempDir -ItemType Directory -Force > $null
            New-Item -Path $oneSubDir -ItemType Directory -Force > $null
            New-Item -Path $oneSubDirPrime -ItemType Directory -Force > $null
            New-Item -Path $twoSubDir -ItemType Directory -Force > $null

            $testCases = @(
                @{ inputStr = "ab"; name = "abc"; localExpected = ".${separator}abc"; oneSubExpected = "..${separator}abc"; twoSubExpected = "..${separator}..${separator}abc" }
                @{ inputStr = "asaasas"; name = "asaasas!popee"; localExpected = ".${separator}asaasas!popee"; oneSubExpected = "..${separator}asaasas!popee"; twoSubExpected = "..${separator}..${separator}asaasas!popee" }
                @{ inputStr = "asaasa"; name = "asaasas!popee"; localExpected = ".${separator}asaasas!popee"; oneSubExpected = "..${separator}asaasas!popee"; twoSubExpected = "..${separator}..${separator}asaasas!popee" }
                @{ inputStr = "bbbbbbbbbb"; name = 'bbbbbbbbbb`'; localExpected = "& '.${separator}bbbbbbbbbb``'"; oneSubExpected = "& '..${separator}bbbbbbbbbb``'"; twoSubExpected = "& '..${separator}..${separator}bbbbbbbbbb``'" }
                @{ inputStr = "bbbbbbbbb"; name = "bbbbbbbbb#"; localExpected = ".${separator}bbbbbbbbb#"; oneSubExpected = "..${separator}bbbbbbbbb#"; twoSubExpected = "..${separator}..${separator}bbbbbbbbb#" }
                @{ inputStr = "bbbbbbbb"; name = "bbbbbbbb{"; localExpected = "& '.${separator}bbbbbbbb{'"; oneSubExpected = "& '..${separator}bbbbbbbb{'"; twoSubExpected = "& '..${separator}..${separator}bbbbbbbb{'" }
                @{ inputStr = "bbbbbbb"; name = "bbbbbbb}"; localExpected = "& '.${separator}bbbbbbb}'"; oneSubExpected = "& '..${separator}bbbbbbb}'"; twoSubExpected = "& '..${separator}..${separator}bbbbbbb}'" }
                @{ inputStr = "bbbbbb"; name = "bbbbbb("; localExpected = "& '.${separator}bbbbbb('"; oneSubExpected = "& '..${separator}bbbbbb('"; twoSubExpected = "& '..${separator}..${separator}bbbbbb('" }
                @{ inputStr = "bbbbb"; name = "bbbbb)"; localExpected = "& '.${separator}bbbbb)'"; oneSubExpected = "& '..${separator}bbbbb)'"; twoSubExpected = "& '..${separator}..${separator}bbbbb)'" }
                @{ inputStr = "bbbb"; name = "bbbb$"; localExpected = "& '.${separator}bbbb$'"; oneSubExpected = "& '..${separator}bbbb$'"; twoSubExpected = "& '..${separator}..${separator}bbbb$'" }
                @{ inputStr = "bbb"; name = "bbb'"; localExpected = "& '.${separator}bbb'''"; oneSubExpected = "& '..${separator}bbb'''"; twoSubExpected = "& '..${separator}..${separator}bbb'''" }
                @{ inputStr = "bb"; name = "bb,"; localExpected = "& '.${separator}bb,'"; oneSubExpected = "& '..${separator}bb,'"; twoSubExpected = "& '..${separator}..${separator}bb,'" }
                @{ inputStr = "b"; name = "b;"; localExpected = "& '.${separator}b;'"; oneSubExpected = "& '..${separator}b;'"; twoSubExpected = "& '..${separator}..${separator}b;'" }
            )

            try {
                Push-Location -Path $tempDir
                foreach ($entry in $testCases) {
                    New-Item -Path $tempDir -Name $entry.name -ItemType File -ErrorAction SilentlyContinue > $null
                }
            } finally {
                Pop-Location
            }
        }

        BeforeEach {
            New-Item -ItemType Directory -Path $caseTestPath > $null
        }

        AfterAll {
            Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
        }

        AfterEach {
            Pop-Location
            Remove-Item -Path $caseTestPath -Recurse -Force -ErrorAction SilentlyContinue
        }

        It "Input '<inputStr>' should successfully complete" -TestCases $testCases {
            param ($inputStr, $localExpected)

            Push-Location -Path $tempDir
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $localExpected
        }

        It "Input '<inputStr>' should successfully complete with relative path '..\'" -TestCases $testCases {
            param ($inputStr, $oneSubExpected)

            Push-Location -Path $oneSubDir
            $inputStr = "..\${inputStr}"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $oneSubExpected
        }

        It "Input '<inputStr>' should successfully complete with relative path '..\..\'" -TestCases $testCases {
            param ($inputStr, $twoSubExpected)

            Push-Location -Path $twoSubDir
            $inputStr = "../../${inputStr}"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $twoSubExpected
        }

        It "Input '<inputStr>' should successfully complete with relative path '..\..\..\ba*\'" -TestCases $testCases {
            param ($inputStr, $twoSubExpected)

            Push-Location -Path $twoSubDir
            $inputStr = "..\..\..\ba*\${inputStr}"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $twoSubExpected
        }

        It "Test relative path" {
            Push-Location -Path $oneSubDir
            $beforeTab = "twoSubDir/../../pri"
            $afterTab = "..${separator}prime"
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Test path with both '\' and '/'" {
            Push-Location -Path $twoSubDir
            $beforeTab = "..\../..\ba*/ab"
            $afterTab = "..${separator}..${separator}abc"
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Test case insensitive <type> path" -Skip:(!$IsLinux) -TestCases @(
            @{ type = "File"     ; beforeTab = "Get-Content f" },
            @{ type = "Directory"; beforeTab = "cd f" }
        ) {
            param ($type, $beforeTab)

            $testItems = "foo", "Foo", "fOO"
            $testItems | ForEach-Object {
                $itemPath = Join-Path $caseTestPath $_
                New-Item -ItemType $type -Path $itemPath
            }
            Push-Location $caseTestPath
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount $testItems.Count

            # order isn't guaranteed so we'll sort them first
            $completions = ($res.CompletionMatches | Sort-Object CompletionText -CaseSensitive).CompletionText -join ":"
            $expected = ($testItems | Sort-Object -CaseSensitive | ForEach-Object { "./$_" }) -join ":"

            $completions | Should -BeExactly $expected
        }

        It "Test case insensitive file and folder path completing for <type>" -Skip:(!$IsLinux) -TestCases @(
            @{ type = "File"     ; beforeTab = "Get-Content f"; expected = "foo","Foo" },  # Get-Content passes thru to provider
            @{ type = "Directory"; beforeTab = "cd f"         ; expected = "Foo" }  # Set-Location is aware of Files vs Folders
        ) {
            param ($beforeTab, $expected)

            $filePath = Join-Path $caseTestPath "foo"
            $folderPath = Join-Path $caseTestPath "Foo"
            New-Item -ItemType File -Path $filePath
            New-Item -ItemType Directory -Path $folderPath
            Push-Location $caseTestPath
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount $expected.Count

            # order isn't guaranteed so we'll sort them first
            $completions = ($res.CompletionMatches | Sort-Object CompletionText -CaseSensitive).CompletionText -join ":"
            $expected = ($expected | Sort-Object -CaseSensitive | ForEach-Object { "./$_" }) -join ":"

        }

        It "PSScriptRoot path completion when AST extent has file identity" {
            $scriptText = '"$PSScriptRoot\BugFix.Tests"'
            $tokens = $null
            $scriptAst = [System.Management.Automation.Language.Parser]::ParseInput(
                $scriptText,
                $PSCommandPath,
                [ref] $tokens,
                [ref] $null)

            $cursorPosition = $scriptAst.Extent.StartScriptPosition.
                GetType().
                GetMethod('CloneWithNewOffset', [System.Reflection.BindingFlags]'NonPublic, Instance').
                Invoke($scriptAst.Extent.StartScriptPosition, @($scriptText.Length - 1))

            $res = TabExpansion2 -ast $scriptAst -tokens $tokens -positionOfCursor $cursorPosition
            $res.CompletionMatches | Should -HaveCount 1
            $expectedPath = Join-Path $PSScriptRoot -ChildPath BugFix.Tests.ps1
            $res.CompletionMatches[0].CompletionText | Should -Be "`"$expectedPath`""
        }

        It "Relative path completion for using <UsingKind> statement when AST extent has file identity" -TestCases @(
            @{UsingKind = "module";  ExpectedFileName = 'UsingFileCompletionModuleTest.psm1'}
            @{UsingKind = "assembly";ExpectedFileName = 'UsingFileCompletionAssemblyTest.dll'}
        ) -test {
            param($UsingKind, $ExpectedFileName)
            $scriptText = "using $UsingKind .\UsingFileCompletion"
            $tokens = $null
            $scriptAst = [System.Management.Automation.Language.Parser]::ParseInput(
                $scriptText,
                (Join-Path -Path $tempDir -ChildPath ScriptInEditor.ps1),
                [ref] $tokens,
                [ref] $null)

            $cursorPosition = $scriptAst.Extent.StartScriptPosition.
                GetType().
                GetMethod('CloneWithNewOffset', [System.Reflection.BindingFlags]'NonPublic, Instance').
                Invoke($scriptAst.Extent.StartScriptPosition, @($scriptText.Length - 1))

            Push-Location -LiteralPath $PSHOME
            $TestFile = Join-Path -Path $tempDir -ChildPath $ExpectedFileName
            $null = New-Item -Path $TestFile
            $res = TabExpansion2 -ast $scriptAst -tokens $tokens -positionOfCursor $cursorPosition
            Pop-Location
                        
            $ExpectedPath = Join-Path -Path '.\' -ChildPath $ExpectedFileName
            $res.CompletionMatches.CompletionText | Where-Object {$_ -Like "*$ExpectedFileName"} | Should -Be $ExpectedPath
        }

        It "Should handle '~' in completiontext when it's used to refer to home in input" {
            $res = TabExpansion2 -inputScript "~$separator"
            # select the first answer which does not have a space in the completion (those completions look like & '3D Objects')
            $observedResult = $res.CompletionMatches.Where({$_.CompletionText.IndexOf("&") -eq -1})[0].CompletionText
            $completedText = $res.CompletionMatches.CompletionText -join ","
            if ($IsWindows) {
                $observedResult | Should -BeLike "$home$separator*" -Because "$completedText"
            } else {
                $observedResult | Should -BeLike "~$separator*" -Because "$completedText"
            }
        }

        It "Should use '~' as relative filter text when not followed by separator" {
            $TempDirName = "~TempDir"
            $TempDirPath = Join-Path -Path $TestDrive -ChildPath "~TempDir"
            $TempDir = New-Item -Path $TempDirPath -ItemType Directory -Force
            Push-Location -Path $TestDrive
            $res = TabExpansion2 -inputScript ~
            $res.CompletionMatches[0].CompletionText | Should -Be ".${separator}${TempDirName}"
        }

        It 'Escapes backtick properly for path: <LiteralPath>' -TestCases @(
            @{LiteralPath = 'BacktickTest[';   BacktickSingle = 1; BacktickDouble = 2;  LiteralBacktickSingle = 0; LiteralBacktickDouble = 0}
            @{LiteralPath = 'BacktickTest`[';  BacktickSingle = 3; BacktickDouble = 6;  LiteralBacktickSingle = 1; LiteralBacktickDouble = 2}
            @{LiteralPath = 'BacktickTest``['; BacktickSingle = 5; BacktickDouble = 10; LiteralBacktickSingle = 2; LiteralBacktickDouble = 4}
            @{LiteralPath = 'BacktickTest$';   BacktickSingle = 0; BacktickDouble = 1;  LiteralBacktickSingle = 0; LiteralBacktickDouble = 1}
            @{LiteralPath = 'BacktickTest`$';  BacktickSingle = 2; BacktickDouble = 3;  LiteralBacktickSingle = 1; LiteralBacktickDouble = 3}
            @{LiteralPath = 'BacktickTest``$'; BacktickSingle = 4; BacktickDouble = 7;  LiteralBacktickSingle = 2; LiteralBacktickDouble = 5}
        ) {
            param($LiteralPath, $BacktickSingle, $BacktickDouble, $LiteralBacktickSingle, $LiteralBacktickDouble)
            $NewPath = Join-Path -Path $TestDrive -ChildPath $LiteralPath
            $null = New-Item -Path $NewPath -Force
            Push-Location $TestDrive

            $InputText = "Get-ChildItem -Path {0}.${separator}BacktickTest"
            $InputTextLiteral = "Get-ChildItem -LiteralPath {0}.${separator}BacktickTest"

            $Text = (TabExpansion2 -inputScript ($InputText -f "'")).CompletionMatches[0].CompletionText
            $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickSingle

            $Text = (TabExpansion2 -inputScript ($InputText -f '"')).CompletionMatches[0].CompletionText
            $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickDouble

            $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f "'")).CompletionMatches[0].CompletionText
            $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickSingle

            $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f '"')).CompletionMatches[0].CompletionText
            $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickDouble

            Remove-Item -LiteralPath $LiteralPath
        }

        It "Should add single quotes if there are double quotes in bare word file path" {
			$BadQuote = [char]8220
		    $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${BadQuote}File"
            $null = New-Item -Path $TestFile1 -Force
            $res = TabExpansion2 -inputScript "Get-ChildItem -Path $TestDrive\"
            ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be "'$TestFile1'"
            Remove-Item -LiteralPath $TestFile1 -Force
        }

        It "Should escape double quote if the input string uses double quotes" {
			$BadQuote = [char]8220
		    $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${BadQuote}File"
            $null = New-Item -Path $TestFile1 -Force
            $res = TabExpansion2 -inputScript "Get-ChildItem -Path `"$TestDrive\"
            $Expected = "`"$($TestFile1.Insert($TestFile1.LastIndexOf($BadQuote), '`'))`""
            ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected
            Remove-Item -LiteralPath $TestFile1 -Force
        }

        It "Should escape single quotes in file paths" {
			$SingleQuote = "'"
		    $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${SingleQuote}File"
            $null = New-Item -Path $TestFile1 -Force
            # Regardless if the input string was singlequoted or not, we expect to add surrounding single quotes and
            # escape the single quote in the file path with another singlequote.
            $Expected = "'$($TestFile1.Insert($TestFile1.LastIndexOf($SingleQuote), "'"))'"

            $res = TabExpansion2 -inputScript "Get-ChildItem -Path '$TestDrive\"
            ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected

            $res = TabExpansion2 -inputScript "Get-ChildItem -Path $TestDrive\"
            ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected

            Remove-Item -LiteralPath $TestFile1 -Force
        }
    }

    It 'Should correct slashes in UNC path completion' -Skip:(!$IsWindows) {
        $Res = TabExpansion2 -inputScript 'Get-ChildItem //localhost/c$/Windows'
        $Res.CompletionMatches[0].CompletionText | Should -Be "'\\localhost\c$\Windows'"
    }

    It 'Should keep custom drive names when completing file paths' {
        $TempDriveName = "asdf"
        $null = New-PSDrive -Name $TempDriveName -PSProvider FileSystem -Root $HOME

        $completions = (TabExpansion2 -inputScript "${TempDriveName}:\")
        # select the first answer which does not have a space in the completion (those completions look like & '3D Objects')
        $observedResult = $completions.CompletionMatches.Where({$_.CompletionText.IndexOf("&") -eq -1})[0].CompletionText
        $completedText = $completions.CompletionMatches.CompletionText -join ","

        $observedResult | Should -BeLike "${TempDriveName}:*" -Because "$completionText"
        Remove-PSDrive -Name $TempDriveName
    }

    Context "Cmdlet name completion" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = "get-ch*item"; expected = "Get-ChildItem" }
                @{ inputStr = "set-alia?"; expected = "Set-Alias" }
                @{ inputStr = "s*-alias"; expected = "Set-Alias" }
                @{ inputStr = "se*-alias"; expected = "Set-Alias" }
                @{ inputStr = "set-al"; expected = "Set-Alias" }
                @{ inputStr = "set-a?i"; expected = "Set-Alias" }
                @{ inputStr = "set-?lias"; expected = "Set-Alias" }
                @{ inputStr = "get-c*ditem"; expected = "Get-ChildItem" }
                @{ inputStr = "Microsoft.PowerShell.Management\get-c*item"; expected = "Microsoft.PowerShell.Management\Get-ChildItem" }
                @{ inputStr = "Microsoft.PowerShell.Utility\set-alia?"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Utility\s*-alias"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Utility\se*-alias"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Utility\set-al"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Utility\set-a?i"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Utility\set-?lias"; expected = "Microsoft.PowerShell.Utility\Set-Alias" }
                @{ inputStr = "Microsoft.PowerShell.Management\get-*ditem"; expected = "Microsoft.PowerShell.Management\Get-ChildItem" }
            )
        }

        It "Input '<inputStr>' should successfully complete" -TestCases $testCases {
            param($inputStr, $expected)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }
    }

    Context "Miscellaneous completion tests" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = "get-childitem -"; expected = "-Path"; setup = $null }
                @{ inputStr = "get-childitem -Fil"; expected = "-Filter"; setup = $null }
                @{ inputStr = '$arg'; expected = '$args'; setup = $null }
                @{ inputStr = '$args.'; expected = 'Count'; setup = $null }
                @{ inputStr = '$Host.UI.Ra'; expected = 'RawUI'; setup = $null }
                @{ inputStr = '$Host.UI.WriteD'; expected = 'WriteDebugLine('; setup = $null }
                @{ inputStr = '$MaximumHistoryCount.'; expected = 'CompareTo('; setup = $null }
                @{ inputStr = '$A=[datetime]::now;$A.'; expected = 'Date'; setup = $null }
                @{ inputStr = '$e=$null;try { 1/0 } catch {$e=$_};$e.'; expected = 'CategoryInfo'; setup = $null }
                @{ inputStr = '$x= gps pwsh;$x.*pm'; expected = 'NPM'; setup = $null }
                @{ inputStr = 'function Get-ScrumData {}; Get-Scrum'; expected = 'Get-ScrumData'; setup = $null }
                @{ inputStr = 'function write-output {param($abcd) $abcd};Write-Output -a'; expected = '-abcd'; setup = $null }
                @{ inputStr = 'function write-output {param($abcd) $abcd};Microsoft.PowerShell.Utility\Write-Output -'; expected = '-InputObject'; setup = $null }
                @{ inputStr = '[math]::Co'; expected = 'CopySign('; setup = $null }
                @{ inputStr = '[math]::PI.GetT'; expected = 'GetType('; setup = $null }
                @{ inputStr = '[math]'; expected = '::E'; setup = $null }
                @{ inputStr = '[math].'; expected = 'Assembly'; setup = $null }
                @{ inputStr = '[math].G'; expected = 'GenericParameterAttributes'; setup = $null }
                @{ inputStr = '[Environment+specialfolder]::App'; expected = 'ApplicationData'; setup = $null }
                @{ inputStr = 'icm {get-pro'; expected = 'Get-Process'; setup = $null }
                @{ inputStr = 'write-output (get-pro'; expected = 'Get-Process'; setup = $null }
                @{ inputStr = 'iex "get-pro'; expected = '"Get-Process"'; setup = $null }
                @{ inputStr = '$variab'; expected = '$variableA'; setup = { $variableB = 2; $variableA = 1 } }
                @{ inputStr = 'a -'; expected = '-keys'; setup = { function a {param($keys) $a} } }
                @{ inputStr = 'Get-Content -Li'; expected = '-LiteralPath'; setup = $null }
                @{ inputStr = 'New-Item -W'; expected = '-WhatIf'; setup = $null }
                @{ inputStr = 'Get-Alias gs'; expected = 'gsn'; setup = $null }
                @{ inputStr = 'Get-Alias -Definition cd'; expected = 'cd..'; setup = $null }
                @{ inputStr = 'remove-psdrive fun'; expected = 'Function'; setup = $null }
                @{ inputStr = 'new-psdrive -PSProvider fi'; expected = 'FileSystem'; setup = $null }
                @{ inputStr = 'Get-PSDrive -PSProvider En'; expected = 'Environment'; setup = $null }
                @{ inputStr = 'remove-psdrive fun'; expected = 'Function'; setup = $null }
                @{ inputStr = 'get-psprovider ali'; expected = 'Alias'; setup = $null }
                @{ inputStr = 'Get-PSDrive -PSProvider Variable '; expected = 'Variable'; setup = $null }
                @{ inputStr = 'Get-Command Get-Chil'; expected = 'Get-ChildItem'; setup = $null }
                @{ inputStr = 'Get-Variable psver'; expected = 'PSVersionTable'; setup = $null }
                @{ inputStr = 'Get-Help get-c*ditem'; expected = 'Get-ChildItem'; setup = $null }
                @{ inputStr = 'Trace-Command e'; expected = 'ETS'; setup = $null }
                @{ inputStr = 'Get-TraceSource e'; expected = 'ETS'; setup = $null }
                @{ inputStr = '[int]:: max'; expected = 'MaxValue'; setup = $null }
                @{ inputStr = '"string". l*'; expected = 'Length'; setup = $null }
                @{ inputStr = '("a" * 5).e'; expected = 'EndsWith('; setup = $null }
                @{ inputStr = '([string][int]1).e'; expected = 'EndsWith('; setup = $null }
                @{ inputStr = '(++$i).c'; expected = 'CompareTo('; setup = $null }
                @{ inputStr = '"a".Length.c'; expected = 'CompareTo('; setup = $null }
                @{ inputStr = '@(1, "a").c'; expected = 'Count'; setup = $null }
                @{ inputStr = '{1}.is'; expected = 'IsConfiguration'; setup = $null }
                @{ inputStr = '@{ }.'; expected = 'Count'; setup = $null }
                @{ inputStr = '@{abc=1}.a'; expected = 'Add('; setup = $null }
                @{ inputStr = '$a.f'; expected = "'fo-o'"; setup = { $a = @{'fo-o'='bar'} } }
                @{ inputStr = 'dir | % { $_.Full'; expected = 'FullName'; setup = $null }
                @{ inputStr = '@{a=$(exit)}.Ke'; expected = 'Keys'; setup = $null }
                @{ inputStr = '@{$(exit)=1}.Va'; expected = 'Values'; setup = $null }
                @{ inputStr = 'switch -'; expected = '-CaseSensitive'; setup = $null }
                @{ inputStr = 'gm -t'; expected = '-Type'; setup = $null }
                @{ inputStr = 'foo -aa -aa'; expected = '-aaa'; setup = { function foo {param($a, $aa, $aaa)} } }
                @{ inputStr = 'switch ( gps -'; expected = '-Name'; setup = $null }
                @{ inputStr = 'set-executionpolicy '; expected = 'AllSigned'; setup = $null }
                @{ inputStr = 'Set-ExecutionPolicy -exe: b'; expected = 'Bypass'; setup = $null }
                @{ inputStr = 'Set-ExecutionPolicy -exe:b'; expected = 'Bypass'; setup = $null }
                @{ inputStr = 'Set-ExecutionPolicy -ExecutionPolicy:'; expected = 'AllSigned'; setup = $null }
                @{ inputStr = 'Set-ExecutionPolicy by -for:'; expected = '$true'; setup = $null }
                @{ inputStr = 'Import-Csv -Encoding '; expected = 'ascii'; setup = $null }
                @{ inputStr = 'Get-Process | % ModuleM'; expected = 'ModuleMemorySize'; setup = $null }
                @{ inputStr = 'Get-Process | % {$_.MainModule} | % Com'; expected = 'Company'; setup = $null }
                @{ inputStr = 'Get-Process | % MainModule | % Com'; expected = 'Company'; setup = $null }
                @{ inputStr = '$p = Get-Process; $p | % ModuleM'; expected = 'ModuleMemorySize'; setup = $null }
                @{ inputStr = 'gmo Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null }
                @{ inputStr = 'rmo Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null }
                @{ inputStr = 'gcm -Module Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null }
                @{ inputStr = 'gcm -ExcludeModule Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null }
                @{ inputStr = 'gmo -list PackageM'; expected = 'PackageManagement'; setup = $null }
                @{ inputStr = 'gcm -Module PackageManagement Find-Pac'; expected = 'Find-Package'; setup = $null }
                @{ inputStr = 'ipmo PackageM'; expected = 'PackageManagement'; setup = $null }
                @{ inputStr = 'Get-Process pws'; expected = 'pwsh'; setup = $null }
                @{ inputStr = "function bar { [OutputType('System.IO.FileInfo')][OutputType('System.Diagnostics.Process')]param() }; bar | ? { `$_.ProcessN"; expected = 'ProcessName'; setup = $null }
                @{ inputStr = "function bar { [OutputType('System.IO.FileInfo')][OutputType('System.Diagnostics.Process')]param() }; bar | ? { `$_.LastAc"; expected = 'LastAccessTime'; setup = $null }
                @{ inputStr = "& 'get-comm"; expected = "'Get-Command'"; setup = $null }
                @{ inputStr = 'alias:dir'; expected = Join-Path 'Alias:' 'dir'; setup = $null }
                @{ inputStr = 'gc alias::ipm'; expected = 'alias::ipmo'; setup = $null }
                @{ inputStr = 'gc enVironment::psmod'; expected = 'enVironment::PSModulePath'; setup = $null }
                ## tab completion safe expression evaluator tests
                @{ inputStr = '@{a=$(exit)}.Ke'; expected = 'Keys'; setup = $null }
                @{ inputStr = '@{$(exit)=1}.Ke'; expected = 'Keys'; setup = $null }
                ## tab completion variable names
                @{ inputStr = '@PSVer'; expected = '@PSVersionTable'; setup = $null }
                @{ inputStr = '$global:max'; expected = '$global:MaximumHistoryCount'; setup = $null }
                @{ inputStr = '$PSMod'; expected = '$PSModuleAutoLoadingPreference'; setup = $null }
                ## tab completion for variable in path
                ## if $PSHOME contains a space tabcompletion adds ' around the path
                @{ inputStr = 'cd $PSHOME\Modu'; expected = if($PSHOME.Contains(' ')) { "'$(Join-Path $PSHOME 'Modules')'" } else { Join-Path $PSHOME 'Modules' }; setup = $null }
                @{ inputStr = 'cd "$PSHOME\Modu"'; expected = "`"$(Join-Path $PSHOME 'Modules')`""; setup = $null }
                @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" }  else { Join-Path $PSHOME 'System.Management.Automation.dll'}; Setup = $null }
                @{ inputStr = '"$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null }
                @{ inputStr = '& "$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null }
                ## tab completion AST-based tests
                @{ inputStr = 'get-date | ForEach-Object { $PSItem.h'; expected = 'Hour'; setup = $null }
                @{ inputStr = '$a=gps;$a[0].h'; expected = 'Handle'; setup = $null }
                @{ inputStr = "`$(1,'a',@{})[-1].k"; expected = 'Keys'; setup = $null }
                @{ inputStr = "`$(1,'a',@{})[1].tri"; expected = 'Trim('; setup = $null }
                ## tab completion for type names
                @{ inputStr = '[ScriptBlockAst'; expected = 'System.Management.Automation.Language.ScriptBlockAst'; setup = $null }
                @{ inputStr = 'New-Object dict'; expected = 'System.Collections.Generic.Dictionary'; setup = $null }
                @{ inputStr = 'New-Object System.Collections.Generic.List[datet'; expected = "'System.Collections.Generic.List[datetime]'"; setup = $null }
                @{ inputStr = '[System.Management.Automation.Runspaces.runspacef'; expected = 'System.Management.Automation.Runspaces.RunspaceFactory'; setup = $null }
                @{ inputStr = '[specialfol'; expected = 'System.Environment+SpecialFolder'; setup = $null }
                ## tab completion for variable names in '{}'
                @{ inputStr = '${PSDefault'; expected = '${PSDefaultParameterValues}'; setup = $null }
            )
        }

        It "Input '<inputStr>' should successfully complete" -TestCases $testCases {
            param($inputStr, $expected, $setup)

            if ($null -ne $setup) { . $setup }
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Contain $expected
        }

        It "Tab completion UNC path" -Skip:(!$IsWindows) {
            $beforeTab = "\\localhost\ADMIN$\boo"
            $afterTab = "& '\\localhost\ADMIN$\Boot'"
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Tab completion UNC path with forward slashes" -Skip:(!$IsWindows) {
            $beforeTab = "//localhost/admin"
            # it is expected that tab completion turns forward slashes into backslashes
            $afterTab = "\\localhost\ADMIN$"
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Tab completion UNC path with filesystem provider" -Skip:(!$IsWindows) {
            $res = TabExpansion2 -inputScript 'Filesystem::\\localhost\admin'
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Filesystem::\\localhost\ADMIN$'
        }

        It "Tab completion for registry" -Skip:(!$IsWindows) {
            $beforeTab = 'registry::HKEY_l'
            $afterTab = 'Registry::HKEY_LOCAL_MACHINE'
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Tab completion for wsman provider" -Skip:(!$IsWindows) {
            $beforeTab = 'wsman::localh'
            $afterTab = 'WSMan::localhost'
            $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
        }

        It "Tab completion for filesystem provider qualified path" {
            $tempFolder = [System.IO.Path]::GetTempPath()
            try
            {
                New-Item -ItemType Directory -Path "$tempFolder/helloworld" > $null
                $tempFolder | Should -Exist
                $beforeTab = 'filesystem::{0}hello' -f $tempFolder
                $afterTab = 'FileSystem::{0}helloworld' -f $tempFolder
                $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length
                $res.CompletionMatches.Count | Should -BeGreaterThan 0
                $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab
            }
            finally
            {
                Remove-Item -Path "$tempFolder/helloworld" -Force -ErrorAction SilentlyContinue
            }
        }

        It "Tab completion dynamic parameter of a custom function" {
            function Test-DynamicParam {
                [CmdletBinding()]
                PARAM( $DeFirst )

                DYNAMICPARAM {
                    $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
                    $attributeCollection = [System.Collections.ObjectModel.Collection[Attribute]]::new()
                    $attributeCollection.Add([Parameter]::new())
                    $deSecond = [System.Management.Automation.RuntimeDefinedParameter]::new('DeSecond', [System.Array], $attributeCollection)
                    $deThird = [System.Management.Automation.RuntimeDefinedParameter]::new('DeThird', [System.Array], $attributeCollection)
                    $null = $paramDictionary.Add('DeSecond', $deSecond)
                    $null = $paramDictionary.Add('DeThird', $deThird)
                    return $paramDictionary
                }

                PROCESS {
                    Write-Host 'Hello'
                    Write-Host $PSBoundParameters
                }
            }

            $inputStr = "Test-DynamicParam -D"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 3
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '-DeFirst'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly '-DeSecond'
            $res.CompletionMatches[2].CompletionText | Should -BeExactly '-DeThird'
        }

        It "Tab completion dynamic parameter '-CodeSigningCert'" -Skip:(!$IsWindows) {
            try {
                Push-Location cert:\
                $inputStr = "gci -co"
                $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
                $res.CompletionMatches[0].CompletionText | Should -BeExactly '-CodeSigningCert'
            } finally {
                Pop-Location
            }
        }

        It "Tab completion for file system takes precedence over functions" {
            try {
                Push-Location $TestDrive
                New-Item -Name myf -ItemType File -Force
                function MyFunction { "Hi there" }

                $inputStr = "myf"
                $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
                $res.CompletionMatches | Should -HaveCount 2
                $res.CompletionMatches[0].CompletionText | Should -BeExactly (Resolve-Path myf -Relative)
                $res.CompletionMatches[1].CompletionText | Should -BeExactly "MyFunction"
            } finally {
                Remove-Item -Path myf -Force
                Pop-Location
            }
        }

        It "Tab completion for validateSet attribute" {
            function foo { param([ValidateSet('cat','dog')]$p) }
            $inputStr = "foo "
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'cat'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'dog'
        }

        It "Tab completion for validateSet attribute takes precedence over enums" {
            function foo { param([ValidateSet('DarkBlue','DarkCyan')][ConsoleColor]$p) }
            $inputStr = "foo "
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'DarkBlue'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'DarkCyan'
        }

        It "Tab completion for attribute type" {
            $inputStr = '[validateset()]$var1'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn 2
            $res.CompletionMatches.CompletionText | Should -Contain 'ValidateSet'
        }

        It "Tab completion for ArgumentCompleter when AST is passed to CompleteInput" {
            $scriptBl = {
                function Test-Completion {
                    param (
                        [String]$TestVal
                    )
                }
                [scriptblock]$completer = {
                    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

                    @('Val1', 'Val2')
                }
                Register-ArgumentCompleter -CommandName Test-Completion -ParameterName TestVal -ScriptBlock $completer
            }
            $pwsh = [PowerShell]::Create()
            $pwsh.AddScript($scriptBl)
            $pwsh.Invoke()

            $completeInput_Input = $scriptBl.ToString()
            $completeInput_Input += "`nTest-Completion -TestVal "
            $res = [System.Management.Automation.CommandCompletion]::CompleteInput($completeInput_Input, $completeInput_Input.Length, $null, $pwsh)
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Val1'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Val2'
        }

        It "Tab completion for enum type parameter of a custom function" {
            function baz ([consolecolor]$name, [ValidateSet('cat','dog')]$p){}
            $inputStr = "baz -name "
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 16
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Black'

            $inputStr = "baz Black "
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'cat'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'dog'
        }

        It "Tab completion for enum members after colon with <Space> space" -TestCases @(
            @{ Space = 0 }
            @{ Space = 1 }
        ) {
            param ($Space)
            $inputStr = "Get-Command -Type:$(' ' * $Space)Al"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Alias'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'All'
        }

        It "Tab completion for enum members between colon with <LeftSpace> space and <RightSpace> space with value" -TestCases @(
            @{ LeftSpace = 0; RightSpace = 0 }
            @{ LeftSpace = 0; RightSpace = 1 }
            @{ LeftSpace = 1; RightSpace = 0 }
            @{ LeftSpace = 1; RightSpace = 1 }
        ) {
            param ($LeftSpace, $RightSpace)
            $inputStrEndsWithCursor = "Get-Command -Type:$(' ' * $LeftSpace)"
            $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)Alias"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length
            $expectedArray = [enum]::GetNames([System.Management.Automation.CommandTypes]) | Sort-Object
            $res.CompletionMatches.CompletionText | Should -Be $expectedArray
        }

        It "Tab completion for enum members between comma with <LeftSpace> space and <RightSpace> space with parameter" -TestCases @(
            @{ LeftSpace = 0; RightSpace = 0 }
            @{ LeftSpace = 0; RightSpace = 1 }
            @{ LeftSpace = 1; RightSpace = 0 }
            @{ LeftSpace = 1; RightSpace = 1 }
        ) {
            param ($LeftSpace, $RightSpace)
            $inputStrEndsWithCursor = "Get-Command -Type Alias,$(' ' * $LeftSpace)"
            $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)-All"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length
            $expectedArray = [enum]::GetNames([System.Management.Automation.CommandTypes]) | Sort-Object
            $res.CompletionMatches.CompletionText | Should -Be $expectedArray
        }

        It "Tab completion for enum members after comma" {
            $inputStr = "Get-Command -Type Alias,c"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Cmdlet'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Configuration'
        }

        It 'Tab completion for enum parameter is filtered against <Name>' -TestCases @(
            @{ Name = 'ValidateRange with enum-values'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)]' }
            @{ Name = 'ValidateRange with int-values'; Attribute = '[ValidateRange(9, 11)]' }
            @{ Name = 'multiple ValidateRange-attributes'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)][ValidateRange([System.ConsoleColor]::Gray, [System.ConsoleColor]::Red)]' }
        ) {
            param($Name, $Attribute)
            $functionDefinition = 'param ( {0}[consolecolor]$color )' -f $Attribute
            Set-Item -Path function:baz -Value $functionDefinition
            $inputStr = 'baz -color '
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 3
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Blue'
            $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Cyan'
            $res.CompletionMatches[2].CompletionText | Should -BeExactly 'Green'
        }

        It 'Tab completion for enum parameter is filtered with ValidateRange using rangekind' {
            $functionDefinition = 'param ( [ValidateRange([System.Management.Automation.ValidateRangeKind]::NonPositive)][consolecolor]$color )' -f $Attribute
            Set-Item -Path function:baz -Value $functionDefinition
            $inputStr = 'baz -color '
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Black' # 0 = NonPositive
        }

        It 'Tab completion of $_ inside incomplete switch condition' {
            $res = TabExpansion2 -inputScript 'Get-PSDrive | Sort-Object -Property {switch ($_.nam'
            $res.CompletionMatches[0].CompletionText | Should -Be 'Name'
        }

        It "Test [CommandCompletion]::GetNextResult" {
            $inputStr = "Get-Command -Type Alias,c"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            $res.GetNextResult($false).CompletionText | Should -BeExactly 'Configuration'
            $res.GetNextResult($true).CompletionText | Should -BeExactly 'Cmdlet'
            $res.GetNextResult($true).CompletionText | Should -BeExactly 'Configuration'
        }

        It "Test history completion" {
            $startDate = Get-Date
            $endDate = $startDate.AddSeconds(1)
            $history = [pscustomobject]@{
                CommandLine = "Test history completion"
                ExecutionStatus = "Stopped"
                StartExecutionTime = $startDate
                EndExecutionTime = $endDate
            }
            Add-History -InputObject $history
            $res = TabExpansion2 -inputScript "#" -cursorColumn 1
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Test history completion"
        }

        It "Test #requires parameter completion" {
            $res = TabExpansion2 -inputScript "#requires -" -cursorColumn 11
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Modules"
        }

        It "Test #requires parameter value completion" {
            $res = TabExpansion2 -inputScript "#requires -PSEdition " -cursorColumn 21
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Core"
        }

        It "Test no completion after #requires -RunAsAdministrator" {
            $res = TabExpansion2 -inputScript "#requires -RunAsAdministrator -" -cursorColumn 31
            $res.CompletionMatches | Should -HaveCount 0
        }

        It "Test no suggestions for already existing parameters in #requires" {
            $res = TabExpansion2 -inputScript "#requires -Modules -" -cursorColumn 20
            $res.CompletionMatches.CompletionText | Should -Not -Contain "Modules"
        }

        It "Test module completion in #requires without quotes" {
            $res = TabExpansion2 -inputScript "#requires -Modules P" -cursorColumn 20
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Contain "Pester"
        }

        It "Test module completion in #requires with quotes" {
            $res = TabExpansion2 -inputScript '#requires -Modules "' -cursorColumn 20
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Contain "Pester"
        }

        It "Test module completion in #requires with multiple modules" {
            $res = TabExpansion2 -inputScript "#requires -Modules Pester," -cursorColumn 26
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Contain "Pester"
        }

        It "Test hashtable key completion in #requires statement for modules" {
            $res = TabExpansion2 -inputScript "#requires -Modules @{"
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "GUID"
        }

        It "Test no suggestions for already existing hashtable keys in #requires statement for modules" {
            $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";' -cursorColumn 41
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Not -Contain "ModuleName"
        }

        It "Test no suggestions for mutually exclusive hashtable keys in #requires statement for modules" {
            $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";RequiredVersion="1.0";' -cursorColumn 63
            $res.CompletionMatches.CompletionText | Should -BeExactly "GUID"
        }

        It "Test no suggestions for RequiredVersion key in #requires statement when ModuleVersion is specified" {
            $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";ModuleVersion="1.0";' -cursorColumn 61
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Not -Contain "RequiredVersion"
        }

        It "Test module completion in #requires statement for hashtables" {
            $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="p' -cursorColumn 34
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches.CompletionText | Should -Contain "Pester"
        }

        It "Test Attribute member completion" {
            $inputStr = "function bar { [parameter(]param() }"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf('(') + 1)
            $res.CompletionMatches | Should -HaveCount 10
            $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Position"
            $entry.CompletionText | Should -BeExactly "Position"
        }

        It "Test Attribute member completion multiple members" {
            $inputStr = "function bar { [parameter(Position,]param() }"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf(',') + 1)
            $res.CompletionMatches | Should -HaveCount 9
            $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Mandatory"
            $entry.CompletionText | Should -BeExactly "Mandatory"
        }

        It "Should complete member in attribute argument value" {
            $inputStr = '[ValidateRange(1,[int]::Maxva^)]$a'
            $CursorIndex = $inputStr.IndexOf('^')
            $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $inputStr.Remove($CursorIndex, 1)
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "MaxValue"
        }

        It "Test Attribute scriptblock completion" {
            $inputStr = '[ValidateScript({Get-Child})]$Test=ls'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf('}'))
            $res.CompletionMatches | Should -HaveCount 1
            $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Get-ChildItem"
            $entry.CompletionText | Should -BeExactly "Get-ChildItem"
        }

        It '<Intent>' -TestCases @(
            @{
                Intent = 'Complete attribute members on empty line'
                Expected = @('Position','ParameterSetName','Mandatory','ValueFromPipeline','ValueFromPipelineByPropertyName','ValueFromRemainingArguments','HelpMessage','HelpMessageBaseName','HelpMessageResourceId','DontShow')
                TestString = @'
function bar { [parameter(


^

        )]param() }
'@
            }
            @{
                Intent = 'Complete attribute members on empty line with preceding member'
                Expected = @('Position','ParameterSetName','Mandatory','ValueFromPipeline','ValueFromPipelineByPropertyName','ValueFromRemainingArguments','HelpMessage','HelpMessageBaseName','HelpMessageResourceId','DontShow')
                TestString = @'
function bar { [parameter(
Mandatory,

^

        )]param() }
'@
            }
        ){
            param($Expected, $TestString)
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
            $res.CompletionMatches[0].CompletionText | Should -BeIn $Expected
        }

        It "Test completion with line continuation" {
            $inputStr = @'
dir -Recurse `
-Lite
'@
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "-LiteralPath"
        }

        It "Test member completion of a static method invocation" {
            $inputStr = '[powershell]::Create().'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 33
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Commands"
        }

        It "Test completion with common parameters" {
            $inputStr = 'invoke-webrequest -out'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 3
            [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-OutBuffer,-OutFile,-OutVariable"
        }

        It "Test completion with exact match" {
            $inputStr = 'get-content -wa'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 3
            [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Wait,-WarningAction,-WarningVariable"
        }

        It "Test completion with splatted variable" {
            $inputStr = 'Get-Content @Splat -P'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 4
            [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-ProgressAction,-PSPath"
        }

        It "Test completion for HttpVersion parameter name" {
            $inputStr = 'Invoke-WebRequest -HttpV'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "-HttpVersion"
        }

        It "Test completion for HttpVersion parameter" {
            $inputStr = 'Invoke-WebRequest -HttpVersion '
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 4
            [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "1.0,1.1,2.0,3.0"
        }

        It "Test completion for HttpVersion parameter with input" {
            $inputStr = 'Invoke-WebRequest -HttpVersion 1'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 2
            [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "1.0,1.1"
        }

        It 'Should complete Select-Object properties without duplicates' {
            $res = TabExpansion2 -inputScript '$PSVersionTable | Select-Object -Property Count,'
            $res.CompletionMatches.CompletionText | Should -Not -Contain "Count"
        }

        It '<Intent>' -TestCases @(
            @{
                Intent = 'Complete loop labels with no input'
                Expected = 'Outer','Inner'
                TestString = ':Outer while ($true){:Inner while ($true){ break ^ }}'
            }
            @{
                Intent = 'Complete loop labels that are accessible'
                Expected = 'Outer'
                TestString = ':Outer do {:Inner while ($true){ break } continue ^ } until ($false)'
            }
            @{
                Intent = 'Complete loop labels with partial input'
                Expected = 'Outer'
                TestString = ':Outer do {:Inner while ($true){ break } continue o^ut } while ($true)'
            }
            @{
                Intent = 'Complete loop label for incomplete switch'
                Expected = 'Outer'
                TestString = ':Outer switch ($x){"randomValue"{ continue ^'
            }
            @{
                Intent = 'Complete loop label for incomplete do loop'
                Expected = 'Outer'
                TestString = ':Outer do {:Inner while ($true){ break } continue ^'
            }
            @{
                Intent = 'Complete loop label for incomplete for loop'
                Expected = 'forLoop'
                TestString = ':forLoop for ($i = 0; $i -lt $SomeCollection.Count; $i++) {continue ^'
            }
            @{
                Intent = 'Complete loop label for incomplete while loop'
                Expected = 'WhileLoop'
                TestString = ':WhileLoop while ($true){ break ^'
            }
            @{
                Intent = 'Complete loop label for incomplete foreach loop'
                Expected = 'foreachLoop'
                TestString = ':foreachLoop foreach ($x in $y) { break ^'
            }
            @{
                Intent = 'Not Complete loop labels with colon'
                Expected = $null
                TestString = ':Outer foreach ($x in $y){:Inner for ($i = 0; $i -lt $X.Count; $i++){ break :O^}}'
            }
            @{
                Intent = 'Not Complete loop labels if cursor is in front of existing label'
                Expected = $null
                TestString = ':Outer switch ($x){"Value1"{break ^ Outer}}'
            }
        ){
            param($Expected, $TestString)
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
            $res.CompletionMatches.CompletionText | Should -BeExactly $Expected
        }
    }

    Context "Module completion for 'using module'" {
        BeforeAll {
            $tempDir = Join-Path -Path $TestDrive -ChildPath "UsingModule"
            New-Item -Path $tempDir -ItemType Directory -Force > $null
            New-Item -Path "$tempDir\testModule.psm1" -ItemType File -Force > $null

            Push-Location -Path $tempDir
        }

        AfterAll {
            Pop-Location
            Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
        }

        It "Test complete module file name" {
            $inputStr = "using module testm"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly ".${separator}testModule.psm1"
        }

        It "Test complete module name" {
            $inputStr = "using module PSRead"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "PSReadLine"
        }

        It "Test complete module name with wildcard" {
            $inputStr = "using module *ReadLi"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "PSReadLine"
        }
    }

    Context "Completion on 'comma', 'redirection' and 'minus' tokens" {
        BeforeAll {
            $tempDir = Join-Path -Path $TestDrive -ChildPath "CommaTest"
            New-Item -Path $tempDir -ItemType Directory -Force > $null
            New-Item -Path "$tempDir\commaA.txt" -ItemType File -Force > $null

            $redirectionTestCases = @(
                @{ inputStr = "gps >";  expected = ".${separator}commaA.txt" }
                @{ inputStr = "gps >>"; expected = ".${separator}commaA.txt" }
                @{ inputStr = "dir con 2>";  expected = ".${separator}commaA.txt" }
                @{ inputStr = "dir con 2>>"; expected = ".${separator}commaA.txt" }
                @{ inputStr = "gps 2>&1>";   expected = ".${separator}commaA.txt" }
                @{ inputStr = "gps 2>&1>>";  expected = ".${separator}commaA.txt" }
            )

            Push-Location -Path $tempDir
        }

        AfterAll {
            Pop-Location
            Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
        }

        It "Test comma with file array element" {
            $inputStr = "dir .\commaA.txt,"
            $expected = ".${separator}commaA.txt"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }

        It "Tab completion for file array element between comma with <LeftSpace> space and <RightSpace> space with parameter" -TestCases @(
            @{ LeftSpace = 0; RightSpace = 0 }
            @{ LeftSpace = 0; RightSpace = 1 }
            @{ LeftSpace = 1; RightSpace = 0 }
            @{ LeftSpace = 1; RightSpace = 1 }
        ) {
            param ($LeftSpace, $RightSpace)
            $inputStrEndsWithCursor = "dir .\commaA.txt,$(' ' * $LeftSpace)"
            $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)-File"
            $expected = ".${separator}commaA.txt"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }

        It "Test comma with Enum array element" {
            $inputStr = "gcm -CommandType Cmdlet,"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount ([System.Enum]::GetNames([System.Management.Automation.CommandTypes]).Count)
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Alias"
        }

        It "Test redirection operator '<inputStr>'" -TestCases $redirectionTestCases {
            param($inputStr, $expected)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }

        It "Test complete the minus token to operators" {
            $inputStr = "55 -"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount ([System.Management.Automation.CompletionCompleters]::CompleteOperator("").Count)
            $res.CompletionMatches[0].CompletionText | Should -BeExactly '-and'
        }
    }

    Context "Folder/File path tab completion with special characters" {
        BeforeAll {
            $tempDir = Join-Path -Path $TestDrive -ChildPath "SpecialChar"
            New-Item -Path $tempDir -ItemType Directory -Force > $null

            New-Item -Path "$tempDir\My [Path]" -ItemType Directory -Force > $null
            New-Item -Path "$tempDir\My [Path]\test.ps1" -ItemType File -Force > $null
            New-Item -Path "$tempDir\)file.txt" -ItemType File -Force > $null

            $testCases = @(
                @{ inputStr = "cd My"; expected = "'.${separator}My ``[Path``]'" }
                @{ inputStr = "Get-Help '.\My ``[Path``]'\"; expected = "'.${separator}My ``[Path``]${separator}test.ps1'" }
                @{ inputStr = "Get-Process >My"; expected = "'.${separator}My ``[Path``]'" }
                @{ inputStr = "Get-Process >'.\My ``[Path``]\'"; expected = "'.${separator}My ``[Path``]${separator}test.ps1'" }
                @{ inputStr = "Get-Process >${tempDir}\My"; expected = "'${tempDir}${separator}My ``[Path``]'" }
                @{ inputStr = "Get-Process > '${tempDir}\My ``[Path``]\'"; expected = "'${tempDir}${separator}My ``[Path``]${separator}test.ps1'" }
            )

            Push-Location -Path $tempDir
        }

        AfterAll {
            Pop-Location
            Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
        }

        It "Complete special relative path '<inputStr>'" -TestCases $testCases {
            param($inputStr, $expected)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }

        It "Complete file name starting with special char" {
            $inputStr = ")"
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "& '.${separator})file.txt'"
        }
    }

    Context "Local tab completion with AST" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = '$p = Get-Process; $p | % ProcessN '; bareWord = 'ProcessN'; expected = 'ProcessName' }
                @{ inputStr = 'function bar { Get-Ali* }'; bareWord = 'Get-Ali*'; expected = 'Get-Alias' }
                @{ inputStr = 'function baz ([string]$version, [consolecolor]$name){} baz version bl'; bareWord = 'bl'; expected = 'Black' }
            )
        }

        It "Input '<inputStr>' should successfully complete via AST" -TestCases $testCases {
            param($inputStr, $bareWord, $expected)

            $tokens = $null
            $ast = [System.Management.Automation.Language.Parser]::ParseInput($inputStr, [ref] $tokens, [ref]$null)
            $elementAst = $ast.Find(
                { $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $args[0].Value -eq $bareWord },
                $true
            )

            $res = TabExpansion2 -ast $ast -tokens $tokens -positionOfCursor $elementAst.Extent.EndScriptPosition
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }
    }

    Context "No tab completion tests" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = 'function new-' }
                @{ inputStr = 'filter new-' }
                @{ inputStr = '@pid.' }
            )
        }

        It "Input '<inputStr>' should not complete to anything" -TestCases $testCases {
            param($inputStr)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -BeNullOrEmpty
        }

        It "A single dash should not complete to anything" {
            function test-{}
            $inputStr = 'git -'
            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches | Should -BeNullOrEmpty
        }
    }

    Context "Tab completion error tests" {
        BeforeAll {
            $ast = {}.Ast;
            $tokens = [System.Management.Automation.Language.Token[]]@()
            $testCases = @(
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::MapStringInputToParsedInput('$PID.', 7)}; expected = "PSArgumentException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($null, $null, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($ast, $null, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($ast, $tokens, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput('$PID.', 7, $null, $null)}; expected = "PSArgumentException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput('$PID.', 5, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($null, $null, $null, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($ast, $null, $null, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($ast, $tokens, $null, $null, $null)}; expected = "PSArgumentNullException" }
                @{ inputStr = {[System.Management.Automation.CommandCompletion]::CompleteInput($ast, $tokens, $ast.Extent.EndScriptPosition, $null, $null)}; expected = "PSArgumentNullException" }
            )
        }

        It "Input '<inputStr>' should throw in tab completion" -TestCases $testCases {
            param($inputStr, $expected)
            $inputStr | Should -Throw -ErrorId $expected
        }

        It "Should not throw errors in tab completion with empty input string" {
            {[System.Management.Automation.CommandCompletion]::CompleteInput("", 0, $null)} | Should -Not -Throw
        }

        It "Should not throw errors in tab completion with empty input ast" {
            {[System.Management.Automation.CommandCompletion]::CompleteInput({}.Ast, @(), {}.Ast.Extent.StartScriptPosition, $null)} | Should -Not -Throw
        }
    }

    Context "DSC tab completion tests" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = 'Configura'; expected = 'Configuration' }
                @{ inputStr = '$extension = New-Object [System.Collections.Generic.List[string]]; $extension.wh'; expected = "Where(" }
                @{ inputStr = '$extension = New-Object [System.Collections.Generic.List[string]]; $extension.fo'; expected = 'ForEach(' }
                @{ inputStr = 'Configuration foo { node $SelectedNodes.'; expected = 'Where(' }
                @{ inputStr = 'Configuration foo { node $SelectedNodes.fo'; expected = 'ForEach(' }
                @{ inputStr = 'Configuration foo { node $AllNodes.'; expected = 'Where(' }
                @{ inputStr = 'Configuration foo { node $ConfigurationData.AllNodes.'; expected = 'Where(' }
                @{ inputStr = 'Configuration foo { node $ConfigurationData.AllNodes.fo'; expected = 'ForEach(' }
                @{ inputStr = 'Configuration bar { File foo { Destinat'; expected = 'DestinationPath = ' }
                @{ inputStr = 'Configuration bar { File foo { Content'; expected = 'Contents = ' }
                @{ inputStr = 'Configuration bar { Fil'; expected = 'File' }
                @{ inputStr = 'Configuration bar { Import-Dsc'; expected = 'Import-DscResource' }
                @{ inputStr = 'Configuration bar { Import-DscResource -Modu'; expected = '-ModuleName' }
                @{ inputStr = 'Configuration bar { Import-DscResource -ModuleName blah -Modu'; expected = '-ModuleVersion' }
                @{ inputStr = 'Configuration bar { Scri'; expected = 'Script' }
                @{ inputStr = 'configuration foo { Script ab {Get'; expected = 'GetScript = ' }
                @{ inputStr = 'configuration foo { Script ab { '; expected = 'DependsOn = ' }
                @{ inputStr = 'configuration foo { File ab { Attributes ='; expected = "'Archive'" }
                @{ inputStr = "configuration foo { File ab { Attributes = "; expected = "'Archive'" }
                @{ inputStr = "configuration foo { File ab { Attributes = ar"; expected = "Archive" }
                @{ inputStr = "configuration foo { File ab { Attributes = 'ar"; expected = "Archive" }
                @{ inputStr = 'configuration foo { File ab { Attributes =('; expected = "'Archive'" }
                @{ inputStr = 'configuration foo { File ab { Attributes =( '; expected = "'Archive'" }
                @{ inputStr = "configuration foo { File ab { Attributes =('Archive',"; expected = "'Hidden'" }
                @{ inputStr = "configuration foo { File ab { Attributes =('Archive', "; expected = "'Hidden'" }
                @{ inputStr = "configuration foo { File ab { Attributes =('Archive', 'Hi"; expected = "Hidden" }
            )
        }

        It "Input '<inputStr>' should successfully complete" -TestCases $testCases -Skip:(!$IsWindows) {
            param($inputStr, $expected)

            if (Test-IsWindowsArm64) {
                Set-ItResult -Pending -Because "TBD"
            }


            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
        }
    }

    Context "CIM cmdlet completion tests" {
        BeforeAll {
            $testCases = @(
                @{ inputStr = "Invoke-CimMethod -ClassName Win32_Process -MethodName Crea"; expected = "Create" }
                @{ inputStr = "Get-CimInstance -ClassName Win32_Process | Invoke-CimMethod -MethodName AttachDeb"; expected = "AttachDebugger" }
                @{ inputStr = 'Get-CimInstance Win32_Process | ?{ $_.ProcessId -eq $PID } | Get-CimAssociatedInstance -ResultClassName Win32_Co*uterSyst'; expected = "Win32_ComputerSystem" }
                @{ inputStr = "Get-CimInstance -ClassName Win32_Environm"; expected = "Win32_Environment" }
                @{ inputStr = "New-CimInstance -ClassName Win32_Environm"; expected = "Win32_Environment" }
                @{ inputStr = 'New-CimInstance -ClassName Win32_Process | %{ $_.Captio'; expected = "Caption" }
                @{ inputStr = "Invoke-CimMethod -ClassName Win32_Environm"; expected = 'Win32_Environment' }
                @{ inputStr = "Get-CimClass -ClassName Win32_Environm"; expected = 'Win32_Environment' }
                @{ inputStr = 'Get-CimInstance -ClassName Win32_Process | Invoke-CimMethod -MethodName SetPriorit'; expected = 'SetPriority' }
                @{ inputStr = 'Invoke-CimMethod -Namespace root/StandardCimv2 -ClassName MSFT_NetIPAddress -MethodName Crea'; expected = 'Create' }
                @{ inputStr = '$win32_process = Get-CimInstance -ClassName Win32_Process; $win32_process | Invoke-CimMethod -MethodName AttachDe'; expected = 'AttachDebugger' }
                @{ inputStr = '$win32_process = Get-CimInstance -ClassName Win32_Process; Invoke-CimMethod -InputObject $win32_process -MethodName AttachDe'; expected = 'AttachDebugger' }
                @{ inputStr = 'Get-CimInstance Win32_Process | ?{ $_.ProcessId -eq $PID } | Get-CimAssociatedInstance -ResultClassName Win32_ComputerS'; expected = 'Win32_ComputerSystem' }
                @{ inputStr = 'Get-CimInstance -Namespace root/Interop -ClassName Win32_PowerSupplyP'; expected = 'Win32_PowerSupplyProfile' }
                @{ inputStr = 'Get-CimInstance __NAMESP'; expected = '__NAMESPACE' }
                @{ inputStr = 'Get-CimInstance -Namespace root/Inter'; expected = 'root/Interop' }
                @{ inputStr = 'Get-CimInstance -Namespace root/Int*ro'; expected = 'root/Interop' }
                @{ inputStr = 'Get-CimInstance -Namespace root/Interop/'; expected = 'root/Interop/ms_409' }
                @{ inputStr = 'New-CimInstance -Namespace root/Inter'; expected = 'root/Interop' }
                @{ inputStr = 'Invoke-CimMethod -Namespace root/Inter'; expected = 'root/Interop' }
                @{ inputStr = 'Get-CimClass -Namespace root/Inter'; expected = 'root/Interop' }
                @{ inputStr = 'Register-CimIndicationEvent -Namespace root/Inter'; expected = 'root/Interop' }
                @{ inputStr = '[Microsoft.Management.Infrastructure.CimClass]$c = $null; $c.CimClassNam'; expected = 'CimClassName' }
                @{ inputStr = '[Microsoft.Management.Infrastructure.CimClass]$c = $null; $c.CimClassName.Substrin'; expected = 'Substring(' }
                @{ inputStr = 'Get-CimInstance -ClassName Win32_Process | %{ $_.ExecutableP'; expected = 'ExecutablePath' }
                @{ inputStr = 'Get-CimInstance -ClassName Win32_Process | Invoke-CimMethod -MethodName SetPriority -Arguments @{'; expected = 'Priority' }
                @{ inputStr = 'Get-CimInstance -ClassName Win32_Service | Invoke-CimMethod -MethodName Change -Arguments @{d'; expected = 'DesktopInteract' }
                @{ inputStr = 'Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{'; expected = 'CommandLine' }
                @{ inputStr = 'New-CimInstance Win32_Environment -Property @{'; expected = 'Caption' }
                @{ inputStr = 'Get-CimInstance Win32_Environment | Set-CimInstance -Property @{'; expected = 'Name' }
                @{ inputStr = 'Set-CimInstance -Namespace root/CIMV'; expected = 'root/CIMV2' }
                @{ inputStr = 'Get-CimInstance Win32_Process -Property '; expected = 'Caption' }
                @{ inputStr = 'Get-CimInstance Win32_Process -Property Caption,'; expected = 'Description' }
            )
            $FailCases = @(
                @{ inputStr = "Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments " }
                @{ inputStr = "New-CimInstance Win32_Process -Property " }
            )
        }

        It "CIM cmdlet input '<inputStr>' should successfully complete" -TestCases $testCases -Skip:(!$IsWindows) {
            param($inputStr, $expected)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches.Count | Should -BeGreaterThan 0
            $res.CompletionMatches[0].CompletionText | Should -Be $expected
        }

        It "CIM cmdlet input '<inputStr>' should not successfully complete" -TestCases $FailCases -Skip:(!$IsWindows) {
            param($inputStr)

            $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length
            $res.CompletionMatches[0].ResultType | should -Not -Be 'Property'
        }
    }

    Context "Module cmdlet completion tests" {
        It "ArugmentCompleter for PSEdition should work for '<cmd>'" -TestCases @(
            @{cmd = "Get-Module -PSEdition "; expected = "Desktop", "Core"}
            @{cmd = "Get-Module -PSEdition '"; expected = "'Desktop'", "'Core'"}
            @{cmd = "Get-Module -PSEdition """; expected = """Desktop""", """Core"""}
            @{cmd = "Get-Module -PSEdition 'Desk"; expected = "'Desktop'"}
            @{cmd = "Get-Module -PSEdition ""Desk"; expected = """Desktop"""}
            @{cmd = "Get-Module -PSEdition Co"; expected = "Core"}
            @{cmd = "Get-Module -PSEdition 'Co"; expected = "'Core'"}
            @{cmd = "Get-Module -PSEdition ""Co"; expected = """Core"""}
        ) {
            param($cmd, $expected)
            $res = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length
            $completionText = $res.CompletionMatches.CompletionText
            $completionText -join ' ' | Should -BeExactly ($expected -join ' ')
        }
    }

    Context "Tab completion help test" {
        BeforeAll {
            New-Item -ItemType File (Join-Path ${TESTDRIVE} "pwsh.xml")
            if ($IsWindows) {
                $userHelpRoot = Join-Path $HOME "Documents/PowerShell/Help/"
            } else {
                $userModulesRoot = [System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::USER_MODULES)
                $userHelpRoot = Join-Path $userModulesRoot -ChildPath ".." -AdditionalChildPath "Help"
            }
        }

        It 'Should complete about help topic' {
            $helpName = "about_Splatting"
            $helpFileName = "${helpName}.help.txt"
            $inputScript = "get-help about_spla"
            $culture = "en-US"
            $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture
            $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture
            $expectedCompletionCount = 0

            ## If help content does not exist, tab completion will not work. So update it first.
            $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName
            $userScopeHelp = Test-Path $userHelpPath
            if ($userScopeHelp) {
                $expectedCompletionCount++
            } else {
                Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser'
                if (Test-Path $userHelpPath) {
                    $expectedCompletionCount++
                }
            }

            $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName)
            if ($allUserScopeHelpPath) {
                $expectedCompletionCount++
            }

            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $inputScript.Length
            $res.CompletionMatches | Should -HaveCount $expectedCompletionCount
            $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName
        }

        It 'Should complete about help topic regardless of culture' {
            try
            {
                ## Save original culture and temporarily set it to da-DK because there's no localized help for da-DK.
                $OriginalCulture = [cultureinfo]::CurrentCulture
                $defaultCulture = "en-US"
                $culture = "da-DK"
                [cultureinfo]::CurrentCulture = $culture
                $helpName = "about_Splatting"
                $helpFileName = "${helpName}.help.txt"

                $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture
                $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture
                $expectedCompletionCount = 0

                ## If help content does not exist, tab completion will not work. So update it first.
                $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName
                $userScopeHelp = Test-Path $userHelpPath
                if ($userScopeHelp) {
                    $expectedCompletionCount++
                }
                else {                    Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser'
                    if (Test-Path $userHelpPath) {
                        $expectedCompletionCount++
                    }
                    else {
                        $aboutHelpPathUserScope = Join-Path $userHelpRoot $defaultCulture
                        $aboutHelpPathAllUsersScope = Join-Path $PSHOME $defaultCulture
                        $userHelpDefaultPath = Join-Path $aboutHelpPathUserScope $helpFileName
                        $userDefaultScopeHelp = Test-Path $userHelpDefaultPath

                        if ($userDefaultScopeHelp) {
                            $expectedCompletionCount++
                        }
                    }
                }

                $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName)
                if ($allUserScopeHelpPath) {
                    $expectedCompletionCount++
                }
                else {
                    $aboutHelpPathAllUsersDefaultScope = Join-Path $PSHOME $defaultCulture
                    $allUsersDefaultScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersDefaultScope $helpFileName)

                    if ($allUsersDefaultScopeHelpPath) {
                        $expectedCompletionCount++
                    }
                }

                $res = TabExpansion2 -inputScript 'get-help about_spla' -cursorColumn 'get-help about_spla'.Length
                $res.CompletionMatches | Should -HaveCount $expectedCompletionCount
                $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName
            }
            finally
            {
                [cultureinfo]::CurrentCulture = $OriginalCulture
            }
        }
        It '<Intent>' -TestCases @(
            @{
                Intent = 'Complete help keywords with minimal input'
                Expected = @(
                    "COMPONENT",
                    "DESCRIPTION",
                    "EXAMPLE",
                    "EXTERNALHELP",
                    "FORWARDHELPCATEGORY",
                    "FORWARDHELPTARGETNAME",
                    "FUNCTIONALITY",
                    "INPUTS",
                    "LINK",
                    "NOTES",
                    "OUTPUTS",
                    "PARAMETER",
                    "REMOTEHELPRUNSPACE",
                    "ROLE",
                    "SYNOPSIS"
                )
                TestString = @'
<#
.^
#>
'@
            }
            @{
                Intent = 'Complete help keywords without duplicates'
                Expected = $null
                TestString = @'
<#
.SYNOPSIS
.S^
#>
'@
            }
            @{
                Intent = 'Complete help keywords with allowed duplicates'
                Expected = 'PARAMETER'
                TestString = @'
<#
.PARAMETER
.Paramet^
#>
'@
            }
            @{
                Intent = 'Complete help keyword FORWARDHELPTARGETNAME argument'
                Expected = 'Get-ChildItem'
                TestString = @'
<#
.FORWARDHELPTARGETNAME  Get-Child^
#>
'@
            }
            @{
                Intent = 'Complete help keyword FORWARDHELPCATEGORY argument'
                Expected = 'Cmdlet'
                TestString = @'
<#
.FORWARDHELPCATEGORY C^
#>
'@
            }
            @{
                Intent = 'Complete help keyword REMOTEHELPRUNSPACE argument'
                Expected = 'PSEdition'
                TestString = @'
<#
.REMOTEHELPRUNSPACE PSEditi^
#>
'@
            }
            @{
                Intent = 'Complete help keyword EXTERNALHELP argument'
                Expected = Join-Path $TESTDRIVE "pwsh.xml"
                TestString = @"
<#
.EXTERNALHELP $TESTDRIVE\pwsh.^
#>
"@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for script'
                Expected = 'Param1'
                TestString = @'
<#
.PARAMETER ^
#>
param($Param1)
'@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for function with help inside'
                Expected = 'param2'
                TestString = @'
function MyFunction ($param1, $param2)
{
<#
.PARAMETER param1
.PARAMETER ^
#>
}
'@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for function with help before it'
                Expected = 'param1','param2'
                TestString = @'
<#
.PARAMETER ^
#>
function MyFunction ($param1, $param2)
{
}
'@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for advanced function with help inside'
                Expected = 'Param1'
                TestString = @'
function Verb-Noun
{
<#
.PARAMETER ^
#>
    [CmdletBinding()]
    Param
    (
        $Param1
    )

    Begin
    {
    }
    Process
    {
    }
    End
    {
    }
}
'@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for nested function with help before it'
                Expected = 'param3','param4'
                TestString = @'
function MyFunction ($param1, $param2)
{
    <#
    .PARAMETER ^
    #>
    function MyFunction2 ($param3, $param4)
    {
    }
}
'@
            }
            @{
                Intent = 'Complete help keyword PARAMETER argument for function inside advanced function'
                Expected = 'param1','param2'
                TestString = @'
function Verb-Noun
{
    Param
    (
        [Parameter()]
        [string[]]
        $ParamA
    )
    Begin
    {
        <#
            .Parameter ^
        #>
        function MyFunction ($param1, $param2)
        {
        }
    }
}
'@
            }
            @{
                Intent = 'Not complete help keyword PARAMETER argument if following function is too far away'
                Expected = $null
                TestString = @'
<#
.PARAMETER ^
#>


function MyFunction ($param1, $param2)
{
}
'@
            }
        ){
            param($Expected, $TestString)
            $CursorIndex = $TestString.IndexOf('^')
            $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1)
            $res.CompletionMatches.CompletionText | Should -BeExactly $Expected
        }
    }

    It 'Should complete module specification keys in using module statement' {
        $res = TabExpansion2 -inputScript 'using module @{'
        $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly "GUID MaximumVersion ModuleName ModuleVersion RequiredVersion"
        $res.CompletionMatches[0].ToolTip | Should -Not -Be $res.CompletionMatches[0].CompletionText
    }

    It 'Should not fallback to file completion when completing typenames' {
        $Text = '[abcdefghijklmnopqrstuvwxyz]'
        $res = TabExpansion2 -inputScript $Text -cursorColumn ($Text.Length - 1)
        $res.CompletionMatches | Should -HaveCount 0
    }
}

Describe "TabCompletion elevated tests" -Tags CI, RequireAdminOnWindows {
    It "Tab completion UNC path with spaces" -Skip:(!$IsWindows) {
        $Share = New-SmbShare -Temporary -ReadAccess (whoami.exe) -Path C:\ -Name "Test Share"
        $res = TabExpansion2 -inputScript '\\localhost\test'
        $res.CompletionMatches[0].CompletionText | Should -BeExactly "& '\\localhost\Test Share'"
        if ($null -ne $Share)
        {
            Remove-SmbShare -InputObject $Share -Force -Confirm:$false
        }
    }
}

Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminOnWindows {
    BeforeAll {
        $skipTest = -not $IsWindows
        $pendingTest = $IsWindows -and (Test-IsWinWow64)

        if (-not $skipTest -and -not $pendingTest) {
            $session = New-RemoteSession
            $powershell = [powershell]::Create()
            $powershell.Runspace = $session.Runspace

            $testCases = @(
                @{ inputStr = 'Get-Proc'; expected = 'Get-Process' }
                @{ inputStr = 'Get-Process | % ProcessN'; expected = 'ProcessName' }
                @{ inputStr = 'Get-ChildItem alias: | % { $_.Defini'; expected = 'Definition' }
            )

            $testCasesWithAst = @(
                @{ inputStr = '$p = Get-Process; $p | % ProcessN '; bareWord = 'ProcessN'; expected = 'ProcessName' }
                @{ inputStr = 'function bar { Get-Ali* }'; bareWord = 'Get-Ali*'; expected = 'Get-Alias' }
                @{ inputStr = 'function baz ([string]$version, [consolecolor]$name){} baz version bl'; bareWord = 'bl'; expected = 'Black' }
            )
        } else {
            $defaultParameterValues = $PSDefaultParameterValues.Clone()

            if ($skipTest) {
                $PSDefaultParameterValues["It:Skip"] = $true
            } elseif ($pendingTest) {
                $PSDefaultParameterValues["It:Pending"] = $true
            }
        }
    }
    AfterAll {
        if (-not $skipTest -and -not $pendingTest) {
            Remove-PSSession $session
            $powershell.Dispose()
        } else {
            $Global:PSDefaultParameterValues = $defaultParameterValues
        }
    }

    It "Input '<inputStr>' should successfully complete in remote runspace" -TestCases $testCases {
        param($inputStr, $expected)
        $res = [System.Management.Automation.CommandCompletion]::CompleteInput($inputStr, $inputStr.Length, $null, $powershell)
        $res.CompletionMatches.Count | Should -BeGreaterThan 0
        $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
    }

    It "Input '<inputStr>' should successfully complete via AST in remote runspace" -TestCases $testCasesWithAst {
        param($inputStr, $bareWord, $expected)

        $tokens = $null
        $ast = [System.Management.Automation.Language.Parser]::ParseInput($inputStr, [ref] $tokens, [ref]$null)
        $elementAst = $ast.Find(
            { $args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $args[0].Value -eq $bareWord },
            $true
        )

        $res = [System.Management.Automation.CommandCompletion]::CompleteInput($ast, $tokens, $elementAst.Extent.EndScriptPosition, $null, $powershell)
        $res.CompletionMatches.Count | Should -BeGreaterThan 0
        $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected
    }
}

Describe "WSMan Config Provider tab complete tests" -Tags Feature,RequireAdminOnWindows {

    BeforeAll {
        $originalDefaultParameterValues = $PSDefaultParameterValues.Clone()
        $PSDefaultParameterValues["it:skip"] = !$IsWindows
    }

    AfterAll {
        $Global:PSDefaultParameterValues = $originalDefaultParameterValues
    }

    It "Tab completion works correctly for Listeners" {
        $path = "wsman:\localhost\listener\listener"
        $res = TabExpansion2 -inputScript $path -cursorColumn $path.Length
        $listener = Get-ChildItem WSMan:\localhost\Listener
        $res.CompletionMatches.Count | Should -Be $listener.Count
        $res.CompletionMatches.ListItemText | Should -BeIn $listener.Name
    }

    It "Tab completion gets dynamic parameters for '<path>' using '<parameter>'" -TestCases @(
        @{path = ""; parameter = "-conn"; expected = "ConnectionURI"},
        @{path = ""; parameter = "-op"; expected = "OptionSet"},
        @{path = ""; parameter = "-au"; expected = "Authentication"},
        @{path = ""; parameter = "-ce"; expected = "CertificateThumbprint"},
        @{path = ""; parameter = "-se"; expected = "SessionOption"},
        @{path = ""; parameter = "-ap"; expected = "ApplicationName"},
        @{path = ""; parameter = "-po"; expected = "Port"},
        @{path = ""; parameter = "-u"; expected = "UseSSL"},
        @{path = "localhost\plugin"; parameter = "-pl"; expected = "Plugin"},
        @{path = "localhost\plugin"; parameter = "-sd"; expected = "SDKVersion"},
        @{path = "localhost\plugin"; parameter = "-re"; expected = "Resource"},
        @{path = "localhost\plugin"; parameter = "-ca"; expected = "Capability"},
        @{path = "localhost\plugin"; parameter = "-xm"; expected = "XMLRenderingType"},
        @{path = "localhost\plugin"; parameter = "-fi"; expected = @("FileName", "File")},
        @{path = "localhost\plugin"; parameter = "-ru"; expected = "RunAsCredential"},
        @{path = "localhost\plugin"; parameter = "-us"; expected = "UseSharedProcess"},
        @{path = "localhost\plugin"; parameter = "-au"; expected = "AutoRestart"},
        @{path = "localhost\plugin"; parameter = "-proc"; expected = "ProcessIdleTimeoutSec"},
        @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-re"; expected = "ResourceUri"},
        @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-ca"; expected = "Capability"}
    ) {
        param($path, $parameter, $expected)
        $script = "new-item wsman:\$path $parameter"
        $res = TabExpansion2 -inputScript $script
        $res.CompletionMatches | Should -HaveCount $expected.Count
        $completionOptions = ""
        foreach ($completion in $res.CompletionMatches) {
            $completionOptions += $completion.ListItemText
        }
        $completionOptions | Should -BeExactly ([string]::Join("", $expected))
    }

    It "Tab completion get dynamic parameters for initialization parameters" -Pending -TestCases @(
        @{path = "localhost\Plugin\microsoft.powershell\InitializationParameters\"; parameter = "-pa"; expected = @("ParamName", "ParamValue")}
    ) {
        # https://github.com/PowerShell/PowerShell/issues/4744
        # TODO: move to test cases above once working
    }

    Context "Tab completion for switch cases on `$PSBoundParameters.Keys" {
        It "Should complete parameter names in switch case for `$PSBoundParameters.Keys" {
            $inputScript = @"
function Test-Func {
    param(
        [string]`$Param1,
        [string]`$Param2,
        [int]`$Count
    )
    switch (`$PSBoundParameters.Keys) {
        P
    }
}
"@
            $cursorPosition = $inputScript.IndexOf("P", $inputScript.IndexOf("Keys)")) + 1
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 2
            $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object
            $completionTexts[0] | Should -BeExactly "Param1"
            $completionTexts[1] | Should -BeExactly "Param2"
        }

        It "Should complete all parameter names when prefix matches single param" {
            $inputScript = @"
function Test-Func {
    param(
        [string]`$Name,
        [int]`$Value
    )
    switch (`$PSBoundParameters.Keys) {
        N
    }
}
"@
            $cursorPosition = $inputScript.IndexOf("N", $inputScript.IndexOf("Keys)")) + 1
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "Name"
        }

        It "Should complete parameter names in scriptblock param" {
            $inputScript = @"
`$sb = {
    param(
        [string]`$ScriptParam1,
        [string]`$ScriptParam2
    )
    switch (`$PSBoundParameters.Keys) {
        S
    }
}
"@
            $cursorPosition = $inputScript.IndexOf("S", $inputScript.IndexOf("Keys)")) + 1
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 2
            $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object
            $completionTexts[0] | Should -BeExactly "ScriptParam1"
            $completionTexts[1] | Should -BeExactly "ScriptParam2"
        }
    }

    Context "Tab completion for `$PSBoundParameters access patterns" {
        It "Should complete parameter names for ContainsKey method" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1, [string]`$Param2, [int]`$Count)
    if (`$PSBoundParameters.ContainsKey('P')) { }
}
"@
            $cursorPosition = $inputScript.IndexOf("'P'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 2
            $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object
            $completionTexts[0] | Should -BeExactly "'Param1'"
            $completionTexts[1] | Should -BeExactly "'Param2'"
        }

        It "Should complete parameter names for indexer access" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1, [string]`$Param2, [int]`$Count)
    `$value = `$PSBoundParameters['P']
}
"@
            $cursorPosition = $inputScript.IndexOf("'P'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 2
            $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object
            $completionTexts[0] | Should -BeExactly "'Param1'"
            $completionTexts[1] | Should -BeExactly "'Param2'"
        }

        It "Should complete parameter names for Remove method" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1, [string]`$Param2, [int]`$Count)
    `$PSBoundParameters.Remove('C')
}
"@
            $cursorPosition = $inputScript.IndexOf("'C'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 1
            $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Count'"
        }

        It "Should complete with double quotes when using double-quoted string" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1, [string]`$Param2)
    if (`$PSBoundParameters.ContainsKey("P")) { }
}
"@
            $cursorPosition = $inputScript.IndexOf('"P"') + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            $res.CompletionMatches | Should -HaveCount 2
            $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object
            $completionTexts[0] | Should -BeExactly '"Param1"'
            $completionTexts[1] | Should -BeExactly '"Param2"'
        }

        It "Should not complete for non-PSBoundParameters variable with indexer" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1)
    `$hash = @{}
    `$value = `$hash['P']
}
"@
            $cursorPosition = $inputScript.IndexOf("'P'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            # Should not return Param1 as completion
            $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" }
            $paramCompletion | Should -BeNullOrEmpty
        }

        It "Should not complete for non-PSBoundParameters variable with ContainsKey" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1)
    `$hash = @{}
    if (`$hash.ContainsKey('P')) { }
}
"@
            $cursorPosition = $inputScript.IndexOf("'P'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            # Should not return Param1 as completion
            $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" }
            $paramCompletion | Should -BeNullOrEmpty
        }

        It "Should not complete for non-PSBoundParameters variable with Remove" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1)
    `$hash = @{}
    `$hash.Remove('P')
}
"@
            $cursorPosition = $inputScript.IndexOf("'P'") + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            # Should not return Param1 as completion
            $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" }
            $paramCompletion | Should -BeNullOrEmpty
        }

        It "Should not complete for non-PSBoundParameters variable with double quotes" {
            $inputScript = @"
function Test-Func {
    param([string]`$Param1)
    `$hash = @{}
    if (`$hash.ContainsKey("P")) { }
}
"@
            $cursorPosition = $inputScript.IndexOf('"P"') + 2
            $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition
            # Should not return Param1 as completion
            $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq '"Param1"' }
            $paramCompletion | Should -BeNullOrEmpty
        }
    }
}