Patchwork [2,of,3] import-checker: make test-module-imports.t work using virtualenv (issue4129)

mail settings
Submitter Chris Jerdonek
Date Dec. 23, 2013, 5:34 a.m.
Message ID <119d2d689169c700ccd2.1387776884@stonewall.local>
Download mbox | patch
Permalink /patch/3226/
State Accepted
Commit f5393a9dc4e545cbc7728706e1b29e7391c1ec4a
Headers show


Chris Jerdonek - Dec. 23, 2013, 5:34 a.m.
# HG changeset patch
# User Chris Jerdonek <>
# Date 1387776038 28800
#      Sun Dec 22 21:20:38 2013 -0800
# Node ID 119d2d689169c700ccd2a84173b02ed510425893
# Parent  a4bfbeba9838ef33ed72942d98ddad0cbf608b2d
import-checker: make test-module-imports.t work using virtualenv (issue4129)

This patch modifies contrib/ so that test-module-imports.t
will pass if run using virtualenv.  The patch achieves this by adding two
new prefixes to the list of allowable sys.path prefixes.  The added prefixes
are the directories of two modules in the stdlib.  The modules selected are
a minimal set that allowed the return value of list_stdlib_modules() to
match the return value without virtualenv, when run on the patch author's
machine: Mac OS X 10.8, Python 2.7.6.


diff --git a/contrib/ b/contrib/
--- a/contrib/
+++ b/contrib/
@@ -2,6 +2,12 @@ 
 import os
 import sys
+# Import a minimal set of stdlib modules needed for list_stdlib_modules()
+# to work when run from a virtualenv.  The modules were chosen empirically
+# so that the return value matches the return value without virtualenv.
+import BaseHTTPServer
+import zlib
 def dotted_name_of_path(path):
     """Given a relative path to a source file, return its dotted module name.
@@ -49,6 +55,21 @@ 
         yield m
     yield 'builtins' # python3 only
     stdlib_prefixes = set([sys.prefix, sys.exec_prefix])
+    # We need to supplement the list of prefixes for the search to work
+    # when run from within a virtualenv.
+    for mod in (BaseHTTPServer, zlib):
+        try:
+            # Not all module objects have a __file__ attribute.
+            filename = mod.__file__
+        except AttributeError:
+            continue
+        dirname = os.path.dirname(filename)
+        for prefix in stdlib_prefixes:
+            if dirname.startswith(prefix):
+                # Then this directory is redundant.
+                break
+        else:
+            stdlib_prefixes.add(dirname)
     for libpath in sys.path:
         # We want to walk everything in sys.path that starts with something
         # in stdlib_prefixes.