@@ -297,6 +297,63 @@ def test_i_works(tmpdir, executor):
297297 run (executor , statement , pgspecial = cli .pgspecial )
298298
299299
300+ @dbtest
301+ def test_watch_works (executor ):
302+ cli = PGCli (pgexecute = executor )
303+
304+ def run_with_watch (
305+ query , target_call_count = 1 , expected_output = "" , expected_timing = None
306+ ):
307+ """
308+ :param query: Input to the CLI
309+ :param target_call_count: Number of times the user lets the command run before Ctrl-C
310+ :param expected_output: Substring expected to be found for each executed query
311+ :param expected_timing: value `time.sleep` expected to be called with on every invocation
312+ """
313+ with mock .patch .object (cli , "echo_via_pager" ) as mock_echo , mock .patch (
314+ "pgcli.main.sleep"
315+ ) as mock_sleep :
316+ mock_sleep .side_effect = [None ] * (target_call_count - 1 ) + [
317+ KeyboardInterrupt
318+ ]
319+ cli .handle_watch_command (query )
320+ # Validate that sleep was called with the right timing
321+ for i in range (target_call_count - 1 ):
322+ assert mock_sleep .call_args_list [i ][0 ][0 ] == expected_timing
323+ # Validate that the output of the query was expected
324+ assert mock_echo .call_count == target_call_count
325+ for i in range (target_call_count ):
326+ assert expected_output in mock_echo .call_args_list [i ][0 ][0 ]
327+
328+ # With no history, it errors.
329+ with mock .patch ("pgcli.main.click.secho" ) as mock_secho :
330+ cli .handle_watch_command (r"\watch 2" )
331+ mock_secho .assert_called ()
332+ assert (
333+ r"\watch cannot be used with an empty query"
334+ in mock_secho .call_args_list [0 ][0 ][0 ]
335+ )
336+
337+ # Usage 1: Run a query and then re-run it with \watch across two prompts.
338+ run_with_watch ("SELECT 111" , expected_output = "111" )
339+ run_with_watch (
340+ "\\ watch 10" , target_call_count = 2 , expected_output = "111" , expected_timing = 10
341+ )
342+
343+ # Usage 2: Run a query and \watch via the same prompt.
344+ run_with_watch (
345+ "SELECT 222; \\ watch 4" ,
346+ target_call_count = 3 ,
347+ expected_output = "222" ,
348+ expected_timing = 4 ,
349+ )
350+
351+ # Usage 3: Re-run the last watched command with a new timing
352+ run_with_watch (
353+ "\\ watch 5" , target_call_count = 4 , expected_output = "222" , expected_timing = 5
354+ )
355+
356+
300357def test_missing_rc_dir (tmpdir ):
301358 rcfile = str (tmpdir .join ("subdir" ).join ("rcfile" ))
302359
0 commit comments