bpo-30759: regrtest: list_cases() now unload modules (#2582)

list_cases() now unload modules, as the test runner does, to prevent
a failure in test_xpickle about test.pickletester loaded after
loading test_cpickle:

./python -m test --list-cases test_cpickle test_xpickle
diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py
index 1290086..fc4681f 100755
--- a/Lib/test/regrtest.py
+++ b/Lib/test/regrtest.py
@@ -289,6 +289,13 @@
     return fmt % test_name
 
 
+def unload_test_modules(save_modules):
+    # Unload the newly imported modules (best effort finalization)
+    for module in sys.modules.keys():
+        if module not in save_modules and module.startswith("test."):
+            test_support.unload(module)
+
+
 def main(tests=None, testdir=None, verbose=0, quiet=False,
          exclude=False, single=False, randomize=False, fromfile=None,
          findleaks=False, use_resources=None, trace=False, coverdir='coverage',
@@ -835,10 +842,8 @@
                     # them again
                     found_garbage.extend(gc.garbage)
                     del gc.garbage[:]
-            # Unload the newly imported modules (best effort finalization)
-            for module in sys.modules.keys():
-                if module not in save_modules and module.startswith("test."):
-                    test_support.unload(module)
+
+            unload_test_modules(save_modules)
 
     if interrupted and not pgo:
         # print a newline after ^C
@@ -1543,6 +1548,7 @@
     test_support.verbose = False
     test_support.match_tests = match_tests
 
+    save_modules = set(sys.modules)
     skipped = []
     for test in selected:
         abstest = get_abs_module(testdir, test)
@@ -1552,6 +1558,8 @@
         except unittest.SkipTest:
             skipped.append(test)
 
+        unload_test_modules(save_modules)
+
     if skipped:
         print >>sys.stderr
         print >>sys.stderr, count(len(skipped), "test"), "skipped:"