run_pytest: improve chdir handling

The current code always chdir's to the top of the chromite dir,
but leaves the user args alone.  When trying to pass in a script,
pytest won't be able to find it anymore.  For example:
$ cd chromite/scripts
$ ./run_pytest cros_unittest.py

This will search for cros_unittest.py in the top chromite dir.

We don't actually need to chdir like this.  The code was added with
the chroot entering logic, and that was because the cros_sdk call
used the default working dir of src/scripts/ instead of telling it
to switch back to the same dir as we started in.

BUG=chromium:1147570
TEST=running tests in topdirs & subdirs still work

Change-Id: Ibab97419a635866761d20a45a77eb317ba512cf9
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/chromite/+/2533475
Reviewed-by: Chris McDonald <cjmcdonald@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
diff --git a/scripts/run_pytest.py b/scripts/run_pytest.py
index 53fdda7..499a559 100644
--- a/scripts/run_pytest.py
+++ b/scripts/run_pytest.py
@@ -35,7 +35,6 @@
     ensure_chroot_exists()
     re_execute_inside_chroot(argv)
   else:
-    os.chdir(constants.CHROMITE_DIR)
     pytest_args += ['--no-chroot']
 
   # This is a cheesy hack to make sure gsutil is populated in the cache before
@@ -81,15 +80,22 @@
 
 def re_execute_inside_chroot(argv):
   """Re-execute the test wrapper inside the chroot."""
+  if cros_build_lib.IsInsideChroot():
+    return
+
+  target = os.path.join(constants.CHROMITE_DIR, 'scripts', 'run_pytest')
+  relpath = os.path.relpath(target, '.')
+  # If we're in the scripts dir, make sure we always have a relative path,
+  # otherwise cros_sdk will search $PATH and fail.
+  if os.path.sep not in relpath:
+    relpath = os.path.join('.', relpath)
   cmd = [
       'cros_sdk',
+      '--working-dir', '.',
       '--',
-      os.path.join('..', '..', 'chromite', 'run_pytest'),
+      relpath,
   ]
-  if not cros_build_lib.IsInsideChroot():
-    os.execvp(cmd[0], cmd + argv)
-  else:
-    os.chdir(constants.CHROMITE_DIR)
+  os.execvp(cmd[0], cmd + argv)
 
 
 def ensure_chroot_exists():