# HG changeset patch
# User Matt Harbison <matt_harbison@yahoo.com>
# Date 1728004090 14400
#      Thu Oct 03 21:08:10 2024 -0400
# Node ID a8e1ff9ac257567808ccce4c9bc9b4eb78568ac3
# Parent  ed90f4a1bb2caa76ccac2f052504269cffaeb468
tests: fix a test hang on Windows when setting a debuglock

I have no idea why, but running the `hg -R auto-upgrade debuglock --set-lock`
command near the end of `test-upgrade-repo.t` hangs the test.  It does
background the process and `killdaemons.py` runs without error, but control
doesn't return to `run-tests.py` until the process is manually killed.  I did
notice that `$!` in MSYS is *not* the PID of the process that got backgrounded,
even when a simple `sleep 60 &` is run in MSYS without the *.t file.  When
`killdaemons.py` is run manually with the PID in ProcessExplorer, the
backgrounded process terminates immediately, and returns control to
`run-tests.py`.

This looks like it would be a race, but the test waits 10s for the lock file to
appear before attempting to kill the process, so there's time.  `hg serve` has a
`--pid-file` option to write the pid to the file, but this is only a debug
command, so I'm not bothering with cluttering the command line.

diff --git a/mercurial/debugcommands.py b/mercurial/debugcommands.py
--- a/mercurial/debugcommands.py
+++ b/mercurial/debugcommands.py
@@ -2238,6 +2238,13 @@
 
     locks = []
     try:
+        # Help the tests out on Windows by writing the correct PID when
+        # invoked by the test harness, before creating the lock.
+        pids = encoding.environ.get(b'DAEMON_PIDS')
+        if pids:
+            with open(pids, "ab") as fp:
+                fp.write(b'%d\n' % os.getpid())
+
         if opts.get('set_wlock'):
             try:
                 locks.append(repo.wlock(False))
diff --git a/tests/test-upgrade-repo.t b/tests/test-upgrade-repo.t
--- a/tests/test-upgrade-repo.t
+++ b/tests/test-upgrade-repo.t
@@ -2103,7 +2103,6 @@
 ----------------------------------------------
 
   $ hg -R auto-upgrade debuglock --set-lock --quiet &
-  $ echo $! >> $DAEMON_PIDS
   $ $RUNTESTDIR/testlib/wait-on-file 10 auto-upgrade/.hg/store/lock
   $ hg status -R auto-upgrade \
   >     --config format.use-dirstate-v2.automatic-upgrade-of-mismatching-repositories=yes \