fork/mons
git clone https://git.julia.blue/fork/mons
4ac910e
main
1import itertools 2import os 3import shutil 4from urllib .parse import urlparse 5 6import click ._termui_impl 7import pytest 8from click .testing import CliRunner 9 10from mons import clickExt 11from mons import install 12 13 14def test_confirm_ext (runner :CliRunner ,test_name ): 15@ click . command 16@ clickExt . yes_option () 17@ clickExt . force_option () 18@ click . option ( "--dangerous" , is_flag = True ) 19def cli (dangerous ): 20return clickExt .confirm_ext (test_name ,default = True ,dangerous = dangerous ) 21 22result = runner .invoke (cli ) 23assert result .exception 24assert "Error: Could not read from stdin" in result .output 25assert "Use '--yes' to skip confirmation prompts." in result .output 26 27result = runner .invoke (cli , ["--yes" ],standalone_mode = False ) 28assert not result .exception 29assert not result .output 30assert result .return_value 31 32result = runner .invoke (cli , ["--yes" ,"--dangerous" ]) 33assert result .exception 34assert "Error: Could not read from stdin" in result .output 35assert "Use '--force' to skip error prompts." in result .output 36 37result = runner .invoke (cli , ["--force" ],standalone_mode = False ) 38assert not result .exception 39assert not result .output 40assert result .return_value 41 42result = runner .invoke (cli , ["--force" ,"--dangerous" ],standalone_mode = False ) 43assert not result .exception 44assert not result .output 45assert result .return_value 46 47 48_test_text_lines = """\ 49mul 50ti 51ple 52 53li 54n 55es 56""" 57 58""" 59we want to verify when text will "overflow" into the pager, and how many lines will be output. 60for testing purposes, if the text overflows there will be no output. 61 62given `text`: 63``` 64AAAAAAAAAA (A*10) 65 66AA 67 68AAAAAA (A*6) 69``` 70and `(cols, rows)`, `lines` (lines + 1 because of \n): 71``` 72(1, 1), 0 73(1, 100), len(text) 74(100, 1), 1 75`` 76""" 77 78_echo_via_pager_text = """\ 79AAAAAAAAAA{_ansi} 80 81AA 82{_ansi} 83AAAAAA 84{_ansi}""" 85""" 865 lines (6 with implicit ending nl) 8744 chars (23 printable) 88 89max printable line length: 10 90""" 91 92_echo_via_pager_text_lines = _echo_via_pager_text .count ("\n" )+ 1 93 94 95@ pytest . mark . parametrize ( 96( "term_size" , "expect_output" ), 97[ 98# extremes 99(( 1 , 1 ), False ), 100(( 99 , 1 ), False ), 101(( 1 , 99 ), True ), 102(( 99 , 99 ), True ), 103# Just big enough 104(( 10 , 6 ), True ), 105# Split twice (two lines split once) 106(( 5 , 7 ), False ), 107(( 5 , 8 ), True ), 108# Split three times (first line split twice) 109(( 4 , 8 ), False ), 110(( 4 , 9 ), True ), 111], 112ids = lambda val : str( val ), 113) 114def test_echo_via_pager (monkeypatch ,capfd ,term_size ,expect_output ): 115monkeypatch .setattr (click ,"echo_via_pager" ,lambda * args ,** kwargs :None ) 116 117# Don't mess with pytest internals 118with monkeypatch .context ()as m : 119m .setattr (shutil ,"get_terminal_size" ,lambda :os .terminal_size (term_size )) 120 121clickExt .echo_via_pager ( 122 [ 123_echo_via_pager_text .format ( 124_ansi = click .style ("" ,fg = "green" ,italic = True ) 125 ) 126 ] 127 ) 128 129out ,err = capfd .readouterr () 130assert not err 131if expect_output : 132assert len (out .splitlines (keepends = True ))== _echo_via_pager_text_lines 133else : 134assert out == "" 135 136 137@ pytest . mark . parametrize ( 138( "input" , "expect" ), 139[ 140( "5" , ( 0 ,)), 141(( "1 2 3 4 5" , True ), ( 0 , 1 , 2 , 3 , 4 )), 142(( "1-3,2-4" , True ), ( 0 , 1 , 2 , 3 )), 143(( "2-1, 5-4" , True ), ( 0 , 1 , 3 , 4 )), 144(( "1-3 ^2 ^3-4 5" , True ), ( 0 , 4 )), 145(( "one four five" , True ), ( 0 , 3 , 4 )), 146(( "1-2 ^1-2 four" , True ), ( 3 ,)), 147(( "1\t2 3 4\t\t \t5" , True ), ( 0 , 1 , 2 , 3 , 4 )), 148(( "1 2,3, 4,\t5," , True ), ( 0 , 1 , 2 , 3 , 4 )), 149( "" , ()), 150( "1-2-3,,32,...lkejgrerg" , ()), 151( " \t " , ()), 152# case-insensitive matching has to be implemented through the find_index parameter 153(( "One, two, FOUR" , True ), ( 1 ,)), 154], 155ids = lambda v : f"(' { v } ')" if isinstance( v , str ) else str( v ), 156) 157def test_prompt_selections (runner ,input ,expect ): 158reverse = False 159if isinstance (input ,tuple ): 160input ,reverse = input 161expect = set (expect ) 162 163@ click . command () 164def cli (): 165selections = [ 166"one" , 167"two" , 168"three" , 169"four" , 170"five" , 171 ] 172 173def find_index (v ): 174try : 175return selections .index (v ) 176except ValueError : 177return None 178 179return clickExt .prompt_selections ( 180selections ,reverse = reverse ,find_index = find_index 181 ) 182 183result = runner .invoke (cli ,input = input ,standalone_mode = False ) 184assert result .return_value == expect 185 186 187@ pytest . mark . prioritize 188def test_type_cast_value (ctx ,test_name ): 189assert clickExt .type_cast_value (ctx ,click .STRING ,test_name )== test_name 190with pytest .raises (click .BadParameter ): 191clickExt .type_cast_value (ctx ,click .INT ,test_name ) 192 193 194def color_cmd (): 195@ click . command () 196@ clickExt . color_option () 197def cmd (color ): 198return color 199 200return cmd 201 202 203@ pytest . mark . parametrize ( 204( "color_arg" , "output" ), 205[ 206( "auto" , None ), 207( "always" , True ), 208( "never" , False ), 209], 210) 211def test_color_option (runner ,color_arg ,output ): 212result = runner .invoke (color_cmd (), ["--color" ,color_arg ],standalone_mode = False ) 213assert result .exit_code == 0 ,result .output 214assert output == result .return_value 215 216 217@ pytest . mark . parametrize (( "env" , "output" ), [({}, None ), ({ "NO_COLOR" : "1" }, False )]) 218def test_color_option_auto (runner ,env ,output ): 219result = runner .invoke (color_cmd (),env = env ,standalone_mode = False ) 220assert result .exit_code == 0 ,result .output 221assert output == result .return_value 222 223 224def test_color_option_bad (runner ): 225result = runner .invoke (color_cmd (), ["--color" ,"invalid" ],standalone_mode = False ) 226assert isinstance (result .exception ,click .BadParameter ) 227assert "Possible values: auto, never, always" in result .exception .message 228 229 230class Fake_UserInfo : 231def __init__ (self ,installs )-> None : 232self .installs = installs 233 234 235def parametrize_bools (* args :str ,filter_cond = None ): 236def filter_param (param ): 237return not filter_cond or filter_cond ( 238** {arg :val for arg ,val in zip (args ,param .values )} 239 ) 240 241params = ( 242pytest .param (* i ,id = ", " .join (itertools .compress (args ,i ))) 243for i in itertools .product ([False ,True ],repeat = len (args )) 244 ) 245 246params = filter (filter_param ,params ) 247return pytest .mark .parametrize (args ,params ) 248 249 250@parametrize_bools( 251"exist" , 252"resolve_install" , 253"check_path" , 254filter_cond = lambda exist , resolve_install , ** k : not ( resolve_install and not exist ), 255) 256def test_install_paramtype ( 257monkeypatch , 258test_name , 259tmp_path , 260ctx , 261exist :bool , 262resolve_install :bool , 263check_path , 264): 265monkeypatch .setattr (clickExt ,"UserInfo" ,Fake_UserInfo ) 266install_path = os .path .join (tmp_path ,test_name ) 267if check_path : 268os .mkdir (install_path ) 269open (os .path .join (install_path ,"Celeste.exe" ),"x" ).close () 270installs = {test_name :install .Install (test_name ,install_path )}if exist else {} 271ctx .obj = Fake_UserInfo (installs ) 272result = clickExt .type_cast_value ( 273ctx , 274clickExt .Install ( 275exist = exist ,resolve_install = resolve_install ,check_path = check_path 276 ), 277test_name , 278 ) 279if resolve_install : 280assert isinstance (result ,install .Install ) 281assert result .name == test_name 282else : 283assert result == test_name 284 285 286def test_install_paramtype_fail (monkeypatch ,test_name ,tmp_path ,ctx ): 287monkeypatch .setattr (clickExt ,"UserInfo" ,Fake_UserInfo ) 288install_path = os .path .join (tmp_path ,test_name ) 289installs = {test_name :install .Install (test_name ,install_path )} 290ctx .obj = Fake_UserInfo (installs ) 291 292def test_install (value ,** kwargs ): 293return clickExt .type_cast_value (ctx ,clickExt .Install (** kwargs ),value ) 294 295with pytest .raises (ValueError ): 296clickExt .Install (exist = False ,resolve_install = True ) 297with pytest .raises (click .ClickException ,match = "does not have a valid path" ): 298test_install (test_name ,check_path = True ) 299with pytest .raises (click .BadParameter ,match = "does not exist" ): 300test_install (test_name + "_doesnotexist" ,exist = True ,check_path = False ) 301with pytest .raises (click .BadParameter ,match = "already exists" ): 302test_install (test_name ,exist = False ) 303 304 305@ pytest . mark . parametrize ( 306( "url_arg" , "expect" ), 307[ 308( "https://mons.coloursofnoise.ca/file" , "{url_arg}" ), 309( "mons.coloursofnoise.ca/file" , "file://{url_arg}" ), 310], 311) 312def test_url_type (runner ,url_arg ,expect ): 313cmd = click .Command ( 314"cmd" , 315params = [click .Argument (["url" ],type = clickExt .URL (default_scheme = "file" ))], 316callback = lambda url :url , 317 ) 318result = runner .invoke (cmd , [url_arg ],standalone_mode = False ) 319assert not result .exception ,result .output 320assert result .return_value == urlparse (expect .format (url_arg = url_arg )) 321 322 323@ pytest . mark . parametrize ( 324( "param_args" , "err" ), 325[ 326({ "valid_schemes" : [ "file" ]}, "URI scheme 'https' not allowed" ), 327({ "require_path" : True }, "Path component required" ), 328], 329) 330def test_url_type_bad (runner ,param_args ,err ): 331cmd = click .Command ( 332"cmd" ,params = [click .Argument (["url" ],type = clickExt .URL (** param_args ))] 333 ) 334result = runner .invoke (cmd , ["https://mons.coloursofnoise.ca" ]) 335assert result .exception 336assert err in result .output 337 338 339class TestCommandExt : 340@ pytest . mark . parametrize ( 341( "args" , "expect" ), [([], None ), ([ "--opt" ], True ), ([ "--opt=value" ], "value" )] 342) 343def test_default_option (self ,runner ,args ,expect ): 344cmd = clickExt .CommandExt ( 345"cmd" , 346params = [ 347clickExt .ExplicitOption (["--opt" ]), 348clickExt .DefaultOption (["--opt" ],is_flag = True ), 349 ], 350callback = lambda opt_default ,opt :opt_default or opt , 351 ) 352 353result = runner .invoke (cmd ,args ,standalone_mode = False ) 354assert result .return_value == expect 355 356def test_placeholder (self ,runner ): 357cmd = clickExt .CommandExt ("cmd" ,params = [clickExt .PlaceHolder (["placeholder" ])]) 358 359result = runner .invoke (cmd ,standalone_mode = False ) 360assert not result .exception 361 362@ pytest . mark . parametrize ( 363( "default" , "exception" ), 364[ 365( None , click . MissingParameter ), 366( lambda : None , click . MissingParameter ), 367( "A Value" , None ), 368( lambda : "A Value" , None ), 369], 370) 371def test_optionalarg (self ,runner ,default ,exception ): 372cmd = clickExt .CommandExt ( 373"cmd" ,params = [clickExt .OptionalArg (["arg" ],default = default )] 374 ) 375 376result = runner .invoke (cmd ,standalone_mode = False ) 377assert exception is None or isinstance (result .exception ,exception ) 378 379def test_help (self ,runner ): 380@ click . command ( 381cls = clickExt . CommandExt , 382usages = [ 383[ "PRIMARY" , "USAGE" ], 384[ "SECONDARY" , "USAGE" ], 385], 386meta_options = { 387"Option Category" : [ 388( 389"--special-option" , 390"Special option description." , 391), 392] 393}, 394) 395@ click . option ( "--flag-metavar" , metavar = "FLAG_METAVAR" , is_flag = True ) 396def cli (): 397"""Standard help message.""" 398 399result = runner .invoke (cli ,"--help" ) 400assert ("SECONDARY USAGE" )in result .output 401assert ("--special-option" )in result .output 402assert ("FLAG_METAVAR" )in result .output